Skip to content

Instantly share code, notes, and snippets.

@sounisi5011
Last active February 19, 2016 00:37
Show Gist options
  • Save sounisi5011/7d6e171d1e5f4f3ad37b to your computer and use it in GitHub Desktop.
Save sounisi5011/7d6e171d1e5f4f3ad37b to your computer and use it in GitHub Desktop.
Get style property (CSSStyleDeclaration object) of Pseudo Elements / 擬似要素のstyleプロパティ(CSSStyleDeclarationオブジェクト)を取得
Get style property (CSSStyleDeclaration object) of Pseudo Elements / 擬似要素のstyleプロパティ(CSSStyleDeclarationオブジェクト)を取得
var contentsElem = document.getElementById('contents');
var contentsBeforeStyle = getPseudoElementStyle(contentsElem, 'before');
contentsBeforeStyle.content = '"::before"';
contentsBeforeStyle.display = 'block';
var contentsAfterStyle = getPseudoElementStyle(contentsElem, 'after');
contentsAfterStyle.content = '"::after"';
contentsAfterStyle.display = 'block';
/*
contentsBeforeStyle === getPseudoElementStyle(contentsElem, 'before') // true
contentsBeforeStyle === getPseudoElementStyle(contentsElem, ':before') // true
contentsBeforeStyle === getPseudoElementStyle(contentsElem, '::before') // false
contentsAfterStyle === getPseudoElementStyle(contentsElem, 'after') // true
contentsAfterStyle === getPseudoElementStyle(contentsElem, ':after') // true
contentsAfterStyle === getPseudoElementStyle(contentsElem, '::after') // false
*/
/* --- */
var notHaveIdElem = document.querySelector('.not_have_id');
var notHaveIdAfterStyle = getPseudoElementStyle(notHaveIdElem, 'after');
notHaveIdAfterStyle.content = '":: " "However, now I have an id attribute: ' + notHaveIdElem.id + '"';
notHaveIdAfterStyle.display = 'block';
notHaveIdAfterStyle.fontWeight = 'bold';
/**
* @license getPseudoElementStyle.js 2016-02-17T18:45Z
* (c) 2016 Sonishi Izuka
* License: MIT
*/
/*!
* getPseudoElementStyle.js 2016-02-17T18:45Z
* (c) 2016 Sonishi Izuka
* License: MIT
*/
(function(global) {
'use strict';
/**
* @type {WeakMap|Object}
* key: !Document
* value: {s: !CSSStyleSheet, c: Object.<string, !CSSStyleDeclaration>}
*/
var styleSheetCacheMap = new (
global.WeakMap ||
/**
* @constructor
*/
function() {
/**
* @type {Array<!Object>}
*/
var keys = [];
/**
* @type {Array<*>}
*/
var values = [];
this.get = function(key) {
var index = keys.indexOf(key);
return -1 < index ? values[index] : undefined;
};
this.set = function(key, value) {
var index = keys.indexOf(key);
if (-1 < index) {
values[index] = value;
} else {
keys.push(key);
values.push(value);
}
};
this.has = function(key) {
return -1 < keys.indexOf(key);
};
}
);
/**
* 擬似要素のスタイル設定をおこなうためのCSSStyleDeclarationオブジェクトを取得する。
*
* Note: この関数は、擬似要素を持つ要素にid属性が無い場合に自動でidを設定します。
*
* @param {!Element} target 擬似要素を持つ要素。この要素にid属性が無い場合、自動でidが割り当てられます。
* @param {string} pseudoElt 擬似要素の種別。CSSセレクタで、`:`の後ろに記述する文字列(`before`, `after`など)を指定します。
* @return {!CSSStyleDeclaration} 擬似要素のスタイルを調節するためのCSSStyleDeclarationオブジェクト。
*/
var getPseudoElementStyle = function(target, pseudoElt) {
/**
* @type {!Document}
*/
var targetDocument = target.ownerDocument || document;
/**
* @type {!Element}
*/
var styleElem;
/**
* @type {string}
*/
var originalId = target.id;
/**
* @type {string}
*/
var id;
/**
* @type {number}
*/
var timestamp;
/**
* @type {number}
*/
var counter;
/**
* @type {string}
*/
var selector;
/**
* @type {{s: !CSSStyleSheet, c: Object.<string, !CSSStyleDeclaration>}}
*/
var styleSheetCache;
/**
* @type {Object.<string, !CSSStyleDeclaration>}
*/
var styleCache;
/**
* @type {!CSSStyleSheet}
*/
var sheet;
/**
* @type {number}
*/
var ruleIndex;
if (styleSheetCacheMap.has(targetDocument)) {
styleSheetCache = styleSheetCacheMap.get(targetDocument);
sheet = styleSheetCache.s;
styleCache = styleSheetCache.c;
} else {
styleElem = targetDocument.createElement('style');
targetDocument.head.appendChild(styleElem);
styleSheetCacheMap.set(targetDocument, {
s: (sheet = styleElem.sheet),
c: (styleCache = {})
});
}
/**
* 対象要素にid属性が無い場合、重複していないランダムなidを生成し設定する
*/
if (!originalId) {
/**
* 'x{タイムスタンプ}-{カウント番号}'の形式でidを生成し、
* そのidを持つ要素がドキュメント内にまだ無い場合、
* 生成したidを要素に割り当てる
*/
timestamp = Date.now();
counter = 0;
do {
id = 'x' + timestamp + '-' + (counter++);
} while (targetDocument.getElementById(id));
target.id = id;
} else {
id = originalId;
}
selector = '#' + id + pseudoElt.replace(/^(?!:)/, ':');
if (originalId && (selector in styleCache)) {
return styleCache[selector];
} else {
ruleIndex = sheet.cssRules.length;
sheet.insertRule(selector + '{}', ruleIndex);
return (styleCache[selector] = sheet.cssRules[ruleIndex].style);
}
};
if (typeof module === 'object' && module !== null && module.exports) {
module.exports = getPseudoElementStyle;
} else if (typeof define === 'function' && define.amd) {
define(function() {
return getPseudoElementStyle;
});
} else {
global.getPseudoElementStyle = getPseudoElementStyle;
}
})(Function('return this')());
/*! getPseudoElementStyle.js 2016-02-17T18:45Z | (c) 2016 Sonishi Izuka | License: MIT */(function(g){function c(e,l){var a=e.ownerDocument||document,b,d=e.id,h,c,g,f;k.has(a)?(f=k.get(a),b=f.b,f=f.a):(b=a.createElement("style"),a.head.appendChild(b),k.set(a,{b:b=b.sheet,a:f={}}));if(d)h=d;else{c=Date.now();g=0;do h="x"+c+"-"+g++;while(a.getElementById(h));e.id=h}a="#"+h+l.replace(/^(?!:)/,":");if(d&&a in f)return f[a];d=b.cssRules.length;b.insertRule(a+"{}",d);return f[a]=b.cssRules[d].style}var k=new (g.WeakMap||function(){var e=[],c=[];this.get=function(a){a=e.indexOf(a);return-1<a?c[a]:void 0};this.set=function(a,b){var d=e.indexOf(a);-1<d?c[d]=b:(e.push(a),c.push(b))};this.has=function(a){return-1<e.indexOf(a)}});"object"===typeof module&&null!==module&&module.exports?module.exports=c:"function"===typeof define&&define.amd?define(function(){return c}):g.getPseudoElementStyle=c})(Function("return this")());
<!DOCTYPE html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<meta name="format-detection" content="telephone=no,email=no,address=no">
<title>Get style property (CSSStyleDeclaration object) of Pseudo Elements</title>
<h1>Get style property (CSSStyleDeclaration object) of Pseudo Elements</h1>
<p id="contents">This is a contents.</p>
<p class="not_have_id">I do not have an id attribute.</p>
<script src="//cdnjs.cloudflare.com/ajax/libs/es5-shim/4.5.4/es5-shim.min.js"></script>
<script src="getPseudoElementStyle.min.js"></script>
<script src="example.js"></script>
The MIT License (MIT)
Copyright (c) 2016 Sonishi Izuka
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment