::before
jQueryを使用してand ::after
(および1つのセミコロンを持つ古いバージョン)などのCSS疑似要素を選択/操作する方法はありますか?
たとえば、私のスタイルシートには次のルールがあります。
.span::after{ content:'foo' }
バニラJSまたはjQueryを使用して「foo」を「bar」に変更するにはどうすればよいですか?
::before
jQueryを使用してand ::after
(および1つのセミコロンを持つ古いバージョン)などのCSS疑似要素を選択/操作する方法はありますか?
たとえば、私のスタイルシートには次のルールがあります。
.span::after{ content:'foo' }
バニラJSまたはjQueryを使用して「foo」を「bar」に変更するにはどうすればよいですか?
また、データ属性を使用してコンテンツを疑似要素に渡し、jQueryを使用してそれを操作することもできます。
HTMLの場合:
<span>foo</span>
jQueryの場合:
$('span').hover(function(){
$(this).attr('data-content','bar');
});
CSSの場合:
span:after {
content: attr(data-content) ' any other text you may want';
}
「他のテキスト」が表示されないようにする場合は、次のようにこれをseucolegaのソリューションと組み合わせることができます。
HTMLの場合:
<span>foo</span>
jQueryの場合:
$('span').hover(function(){
$(this).addClass('change').attr('data-content','bar');
});
CSSの場合:
span.change:after {
content: attr(data-content) ' any other text you may want';
}
これは、jQueryが実行できる他のすべてのことを含めて、答えるのが簡単な質問だと思うでしょう。残念ながら、問題は技術的な問題に帰着します。css:afterおよび:beforeルールはDOMの一部ではないため、jQueryのDOMメソッドを使用して変更することはできません。
JavaScriptやCSSの回避策を使用してこれらの要素を操作する方法があります。どちらを使用するかは、正確な要件によって異なります。
「最良の」アプローチと広く考えられているものから始めます。
このアプローチでは、CSSに別のスタイル:after
または:before
スタイルのクラスをすでに作成しています。この「新しい」クラスを後でスタイルシートに配置して、以下をオーバーライドするようにします。
p:before {
content: "foo";
}
p.special:before {
content: "bar";
}
次に、jQuery(またはバニラJavaScript)を使用して、このクラスを簡単に追加または削除できます。
$('p').on('click', function() {
$(this).toggleClass('special');
});
$('p').on('click', function() {
$(this).toggleClass('special');
});
p:before {
content: "foo";
color: red;
cursor: pointer;
}
p.special:before {
content: "bar";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
:before
。:after
:after
JavaScriptを使用して、スタイルを含むスタイルをドキュメントのスタイルシートに直接追加することができ:before
ます。jQueryは便利なショートカットを提供しませんが、幸いなことにJSはそれほど複雑ではありません。
var str = "bar";
document.styleSheets[0].addRule('p.special:before','content: "'+str+'";');
var str = "bar";
document.styleSheets[0].addRule('p.special:before', 'content: "' + str + '";');
p:before {
content: "foo";
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="special">This is a paragraph</p>
<p>This is another paragraph</p>
.addRule()
そして、関連する.insertRule()
メソッドは、今日かなりよくサポートされています。
バリエーションとして、jQueryを使用してまったく新しいスタイルシートをドキュメントに追加することもできますが、必要なコードはよりクリーンではありません。
var str = "bar";
$('<style>p.special:before{content:"'+str+'"}</style>').appendTo('head');
var str = "bar";
$('<style>p.special:before{content:"' + str + '"}</style>').appendTo('head');
p:before {
content: "foo";
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="special">This is a paragraph</p>
<p>This is another paragraph</p>
値を追加するだけでなく、値を「操作」することについて話している場合は、別のアプローチを使用して既存のスタイルまたはスタイルを読み取ることもできます。:after
:before
var str = window.getComputedStyle(document.querySelector('p'), ':before')
.getPropertyValue('content');
var str = window.getComputedStyle($('p')[0], ':before').getPropertyValue('content');
console.log(str);
document.styleSheets[0].addRule('p.special:before', 'content: "' + str+str + '";');
p:before {
content:"foo";
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="special">This is a paragraph</p>
<p>This is another paragraph</p>
jQueryを使用document.querySelector('p')
する場合は、コードを少し短くするために、に置き換えることができます。$('p')[0]
CSSで使用attr()
して、特定のDOM属性を読み取ることもできます。(ブラウザがをサポートしている場合は:before
、それもサポートattr()
します。)これをcontent:
慎重に準備されたCSSと組み合わせることで、次のコンテンツ(マージンや色などの他のプロパティは変更できません:before
)を:after
動的に変更できます。
p:before {
content: attr(data-before);
color: red;
cursor: pointer;
}
JS:
$('p').on('click', function () {
$(this).attr('data-before','bar');
});
$('p').on('click', function () {
$(this).attr('data-before','bar');
});
p:before {
content: attr(data-before);
color: red;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
CSSを事前に準備できない場合は、これを2番目の手法と組み合わせることができます。
var str = "bar";
document.styleSheets[0].addRule('p:before', 'content: attr(data-before);');
$('p').on('click', function () {
$(this).attr('data-before', str);
});
var str = "bar";
document.styleSheets[0].addRule('p:before', 'content: attr(data-before) !important;');
$('p').on('click', function() {
$(this).attr('data-before', str);
});
p:before {
content: "foo";
color: red;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
attr
CSSでは、コンテンツ文字列にのみ適用でき、URLやRGBカラーには適用できませんこれらはCSSを介してブラウザによって他の実際のDOM要素のようにレンダリングされますが、疑似要素自体はDOMの一部ではありません。これは、名前が示すように、疑似要素は実際の要素ではないため、できないためです。それらを選択して、jQuery(またはSelectors APIでさえも、そのことについては任意のJavaScript API )を使用して直接操作します。これは、とだけでなく、スクリプトでスタイルを変更しようとしている疑似要素に適用されます。::before
::after
疑似要素スタイルに直接アクセスできるのは、CSSOM(think)を介してのみです。これは、疑似要素もサポートしないメソッドであるwindow.getComputedStyle()
jQueryによって公開されません。.css()
ただし、他の方法をいつでも見つけることができます。たとえば、次のようになります。
1つ以上の任意のクラスの疑似要素にスタイルを適用してから、クラスを切り替えます(簡単な例については、 seucolegaの回答を参照してください)。これは、単純なセレクター(疑似要素ではない)を使用する慣用的な方法です。要素と要素の状態を区別し、それらが使用されることを意図している方法
ドキュメントのスタイルシートを変更することにより、前述の疑似要素に適用されているスタイルを操作します。これは、ハックのようなものです。
疑似要素はDOMの一部ではないため、jQueryで選択することはできません。ただし、特定のクラスを親要素に追加し、CSSでその疑似要素を制御することができます。
jQueryの場合:
<script type="text/javascript">
$('span').addClass('change');
</script>
CSSの場合:
span.change:after { content: 'bar' }
疑似要素を操作するために、カスタムプロパティ(別名CSS変数)に依存することもできます。仕様で次のことを読み取ることができます。
カスタムプロパティは通常のプロパティであるため、任意の要素で宣言でき、通常の継承とカスケード ルールで解決され、@ mediaやその他の条件付きルールで条件付きにでき、HTMLのスタイル属性で使用でき、読み取りまたは設定できますCSSOMなどを使用します。
これを考慮すると、要素内にカスタムプロパティを定義するという考え方があり、疑似要素はそれを単純に継承します。したがって、簡単に変更できます。
1)インラインスタイルの使用:
.box:before {
content:var(--content,"I am a before element");
color:var(--color, red);
font-size:25px;
}
<div class="box"></div>
<div class="box" style="--color:blue;--content:'I am a blue element'"></div>
<div class="box" style="--color:black"></div>
<div class="box" style="--color:#f0f;--content:'another element'"></div>
2)CSSとクラスの使用
.box:before {
content:var(--content,"I am a before element");
color:var(--color, red);
font-size:25px;
}
.blue {
--color:blue;
--content:'I am a blue element';
}
.black {
--color:black;
}
<div class="box"></div>
<div class="box black" ></div>
<div class="box blue"></div>
3)javascriptを使用する
document.querySelectorAll('.box')[0].style.setProperty("--color", "blue");
document.querySelectorAll('.box')[1].style.setProperty("--content", "'I am another element'");
.box:before {
content:var(--content,"I am a before element");
color:var(--color, red);
font-size:25px;
}
<div class="box"></div>
<div class="box"></div>
4)jQueryの使用
$('.box').eq(0).css("--color", "blue");
/* the css() function with custom properties works only with a jQuery vesion >= 3.x
with older version we can use style attribute to set the value. Simply pay
attention if you already have inline style defined!
*/
$('.box').eq(1).attr("style","--color:#f0f");
.box:before {
content:"I am a before element";
color:var(--color, red);
font-size:25px;
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
複雑な値で使用することもできます。
.box {
--c:"content";
--b:linear-gradient(red,blue);
--s:20px;
--p:0 15px;
}
.box:before {
content: var(--c);
background:var(--b);
color:#fff;
font-size: calc(2 * var(--s) + 5px);
padding:var(--p);
}
<div class="box"></div>
var(--c,value)
がデフォルト値でvalue
あり、フォールバック値とも呼ばれる構文を検討していることに気付くかもしれません。
同じ仕様から、次のように読み取ることができます。
カスタムプロパティの値は、var()関数を使用して別のプロパティの値に置き換えることができます。var()の構文は次のとおりです。
var() = var( <custom-property-name> [, <declaration-value> ]? )
関数の最初の引数は、置換されるカスタムプロパティの名前です。関数の2番目の引数は、指定されている場合、フォールバック値です。これは、参照されるカスタムプロパティが無効な場合に置換値として使用されます。
以降:
プロパティの値にvar()を代入するには、次のようにします。
- 関数の最初の引数で指定されたカスタムプロパティ
var()
がアニメーションで汚染されており、var()
関数がアニメーションプロパティまたはそのロングハンドのいずれかで使用されている場合は、カスタムプロパティをこのアルゴリズムの残りの部分の初期値を持つものとして扱います。- 関数の最初の引数で指定されたカスタムプロパティの値が初期値以外の場合は、関数を対応するカスタムプロパティの
var()
値に置き換えます。var()
- それ以外の場合、
var()
関数の2番目の引数としてフォールバック値がある場合は、関数をフォールバック値に置き換えvar()
ます。var()
フォールバックに参照がある場合は、それらも置き換えます。- それ以外の場合、関数を含むプロパティ
var()
は計算値の時点では無効です。
カスタムプロパティを設定しない場合、または設定する場合、initial
または無効な値が含まれている場合は、フォールバック値が使用されます。カスタムプロパティをデフォルト値にリセットする場合は、の使用initial
が役立ちます。
関連している
クリスチャンが示唆していることと同じように、あなたも次のことができます。
$('head').append("<style>.span::after{ content:'bar' }</style>");
cssで定義されている:afterおよび:beforeスタイルプロパティにアクセスする方法は次のとおりです。
// Get the color value of .element:before
var color = window.getComputedStyle(
document.querySelector('.element'), ':before'
).getPropertyValue('color');
// Get the content value of .element:before
var content = window.getComputedStyle(
document.querySelector('.element'), ':before'
).getPropertyValue('content');
::beforeまたは::aftersudo要素を完全にCSSで操作したい場合は、JSで行うことができます。下記参照;
jQuery('head').append('<style id="mystyle" type="text/css"> /* your styles here */ </style>');
要素にIDがあることに注意<style>
してください。これを使用して、スタイルが動的に変更された場合に、要素を削除して再度追加することができます。
このように、要素はJSの助けを借りて、CSSを介して希望どおりのスタイルになります。
皆さん、ありがとうございました!私はなんとかやりたかったことをすることができました: Dhttp: //jsfiddle.net/Tfc9j/42/ ここで見てください
外側のdivの不透明度を、内側のdivの不透明度とは異なり、クリックするだけで変化するようにしたかったのです;)ありがとうございます。
$('#ena').on('click', function () {
$('head').append("<style>#ena:before { opacity:0.3; }</style>");
});
$('#duop').on('click', function (e) {
$('head').append("<style>#ena:before { opacity:0.8; }</style>");
e.stopPropagation();
});
#ena{
width:300px;
height:300px;
border:1px black solid;
position:relative;
}
#duo{
opacity:1;
position:absolute;
top:50px;
width:300px;
height:100px;
background-color:white;
}
#ena:before {
content: attr(data-before);
color: white;
cursor: pointer;
position: absolute;
background-color:red;
opacity:0.9;
width:100%;
height:100%;
}
<div id="ena">
<div id="duo">
<p>ena p</p>
<p id="duop">duoyyyyyyyyyyyyyy p</p>
</div>
</div>
効果的ではあるがあまり効率的ではない方法の1つは、新しいコンテンツを含むルールをドキュメントに追加し、それをクラスで参照することです。必要なものに応じて、クラスはコンテンツの値ごとに一意のIDを必要とする場合があります。
$("<style type='text/css'>span.id-after:after{content:bar;}</style>").appendTo($("head"));
$('span').addClass('id-after');
HTMLは次のとおりです。
<div class="icon">
<span class="play">
::before
</span>
</div>
'前'の計算されたスタイルはcontent: "VERIFY TO WATCH";
これが私の2行のjQueryで、この要素を具体的に参照するためにクラスを追加し、次にスタイルタグ(!importantタグ付き)を追加してsudo要素のコンテンツ値のCSSを変更するというアイデアを使用しています。
$("span.play:eq(0)").addClass('G');
$('body').append("<style>.G:before{content:'NewText' !important}</style>");
偽のプロパティを作成するか、既存のプロパティを使用して、それを疑似要素のスタイルシートに継承することができます。
var switched = false;
// Enable color switching
setInterval(function () {
var color = switched ? 'red' : 'darkred';
var element = document.getElementById('arrow');
element.style.backgroundColor = color;
// Managing pseudo-element's css
// using inheritance.
element.style.borderLeftColor = color;
switched = !switched;
}, 1000);
.arrow {
/* SET FICTIONAL PROPERTY */
border-left-color:red;
background-color:red;
width:1em;
height:1em;
display:inline-block;
position:relative;
}
.arrow:after {
border-top:1em solid transparent;
border-right:1em solid transparent;
border-bottom:1em solid transparent;
border-left:1em solid transparent;
/* INHERIT PROPERTY */
border-left-color:inherit;
content:"";
width:0;
height:0;
position:absolute;
left:100%;
top:-50%;
}
<span id="arrow" class="arrow"></span>
「content」プロパティでは機能しないようです:(
達成できることの例を示すためだけに、これを実際の使用のために書いたわけではないので、これは実用的ではありません。
css = {
before: function(elem,attr){
if($("#cust_style") !== undefined){
$("body").append("<style> " + elem + ":before {" + attr + "} </style>");
} else {
$("#cust_style").remove();
$("body").append("<style> " + elem + ":before {" + attr + "} </style>");
}
}, after: function(elem,attr){
if($("#cust_style") !== undefined){
$("body").append("<style> " + elem + ":after {" + attr + "} </style>");
} else { $("#cust_style").remove();
$("body").append("<style> " + elem + ":after {" + attr + "} </style>");
}
}
}
これは現在、/を追加するか、Pseudo要素の後のターゲット要素に影響を与える必要な属性を含むStyle要素を追加します。
これは次のように使用できます
css.after("someElement"," content: 'Test'; position: 'absolute'; ") // editing / adding styles to :after
と
css.before( ... ); // to affect the before pseudo element.
後:および前:疑似要素はDOMを介して直接アクセスできません。現在、cssの特定の値を自由に編集することはできません。
私のやり方は単なる例であり、練習には適していません。独自のトリックをいくつか試して、実際の使用法に合わせて修正することができます。
だから、これと他の人とあなた自身の実験をしてください!
よろしく-アダーシュヘグデ。
私はいつも自分のutils関数を追加しています。これは次のようになります。
function setPseudoElContent(selector, value) {
document.styleSheets[0].addRule(selector, 'content: "' + value + '";');
}
setPseudoElContent('.class::after', 'Hello World!');
またはES6の機能を利用します。
const setPseudoElContent = (selector, value) => {
document.styleSheets[0].addRule(selector, `content: "${value}";`);
}
setPseudoElContent('.class::after', 'Hello World!');
ここには多くの答えがありますが、受け入れられたものでさえも、:before
またはのcssを操作するのに役立つ答えはありません。:after
これが私がそれをすることを提案する方法です。HTMLが次のようになっているとしましょう。
<div id="something">Test</div>
そして、CSSで:beforeを設定し、次のように設計します。
#something:before{
content:"1st";
font-size:20px;
color:red;
}
#something{
content:'1st';
}
content
後で簡単に取り出せるように、要素自体にも属性を設定していることに注意してください。次に、button
クリックがあります。:beforeの色を緑に変更し、フォントサイズを30pxに変更します。あなたは次のようにそれを達成することができます:
いくつかのクラスで必要なスタイルでcssを定義します.activeS
:
.activeS:before{
color:green !important;
font-size:30px !important;
}
次のように:before要素にクラスを追加することで:beforeスタイルを変更できます。
<button id="changeBefore">Change</button>
<script>
$('#changeBefore').click(function(){
$('#something').addClass('activeS');
});
</script>
のコンテンツを取得したいだけの場合は:before
、次のように実行できます。
<button id="getContent">Get Content</button>
<script>
$('#getContent').click(function(){
console.log($('#something').css('content'));//will print '1st'
});
</script>
最終的に、jQueryによってコンテンツを動的に変更したい場合は:before
、次のように実現できます。
<button id="changeBefore">Change</button>
<script>
var newValue = '22';//coming from somewhere
var add = '<style>#something:before{content:"'+newValue+'"!important;}</style>';
$('#changeBefore').click(function(){
$('body').append(add);
});
</script>
上記の「changeBefore」ボタンをクリックすると、の:before
内容が#something
動的な値である「22」に変更されます。
お役に立てば幸いです
style
頭にを追加できるのに、なぜクラスや属性を追加するのか
$('head').append('<style>.span:after{ content:'changed content' }</style>')
この目的のために私のプラグインを使用できます。
JQuery:
(function() {
$.pseudoElements = {
length: 0
};
var setPseudoElement = function(parameters) {
if (typeof parameters.argument === 'object' || (parameters.argument !== undefined && parameters.property !== undefined)) {
for (var element of parameters.elements.get()) {
if (!element.pseudoElements) element.pseudoElements = {
styleSheet: null,
before: {
index: null,
properties: null
},
after: {
index: null,
properties: null
},
id: null
};
var selector = (function() {
if (element.pseudoElements.id !== null) {
if (Number(element.getAttribute('data-pe--id')) !== element.pseudoElements.id) element.setAttribute('data-pe--id', element.pseudoElements.id);
return '[data-pe--id="' + element.pseudoElements.id + '"]::' + parameters.pseudoElement;
} else {
var id = $.pseudoElements.length;
$.pseudoElements.length++
element.pseudoElements.id = id;
element.setAttribute('data-pe--id', id);
return '[data-pe--id="' + id + '"]::' + parameters.pseudoElement;
};
})();
if (!element.pseudoElements.styleSheet) {
if (document.styleSheets[0]) {
element.pseudoElements.styleSheet = document.styleSheets[0];
} else {
var styleSheet = document.createElement('style');
document.head.appendChild(styleSheet);
element.pseudoElements.styleSheet = styleSheet.sheet;
};
};
if (element.pseudoElements[parameters.pseudoElement].properties && element.pseudoElements[parameters.pseudoElement].index) {
element.pseudoElements.styleSheet.deleteRule(element.pseudoElements[parameters.pseudoElement].index);
};
if (typeof parameters.argument === 'object') {
parameters.argument = $.extend({}, parameters.argument);
if (!element.pseudoElements[parameters.pseudoElement].properties && !element.pseudoElements[parameters.pseudoElement].index) {
var newIndex = element.pseudoElements.styleSheet.rules.length || element.pseudoElements.styleSheet.cssRules.length || element.pseudoElements.styleSheet.length;
element.pseudoElements[parameters.pseudoElement].index = newIndex;
element.pseudoElements[parameters.pseudoElement].properties = parameters.argument;
};
var properties = '';
for (var property in parameters.argument) {
if (typeof parameters.argument[property] === 'function')
element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property]();
else
element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property];
};
for (var property in element.pseudoElements[parameters.pseudoElement].properties) {
properties += property + ': ' + element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';
};
element.pseudoElements.styleSheet.addRule(selector, properties, element.pseudoElements[parameters.pseudoElement].index);
} else if (parameters.argument !== undefined && parameters.property !== undefined) {
if (!element.pseudoElements[parameters.pseudoElement].properties && !element.pseudoElements[parameters.pseudoElement].index) {
var newIndex = element.pseudoElements.styleSheet.rules.length || element.pseudoElements.styleSheet.cssRules.length || element.pseudoElements.styleSheet.length;
element.pseudoElements[parameters.pseudoElement].index = newIndex;
element.pseudoElements[parameters.pseudoElement].properties = {};
};
if (typeof parameters.property === 'function')
element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property();
else
element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property;
var properties = '';
for (var property in element.pseudoElements[parameters.pseudoElement].properties) {
properties += property + ': ' + element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';
};
element.pseudoElements.styleSheet.addRule(selector, properties, element.pseudoElements[parameters.pseudoElement].index);
};
};
return $(parameters.elements);
} else if (parameters.argument !== undefined && parameters.property === undefined) {
var element = $(parameters.elements).get(0);
var windowStyle = window.getComputedStyle(
element, '::' + parameters.pseudoElement
).getPropertyValue(parameters.argument);
if (element.pseudoElements) {
return $(parameters.elements).get(0).pseudoElements[parameters.pseudoElement].properties[parameters.argument] || windowStyle;
} else {
return windowStyle || null;
};
} else {
console.error('Invalid values!');
return false;
};
};
$.fn.cssBefore = function(argument, property) {
return setPseudoElement({
elements: this,
pseudoElement: 'before',
argument: argument,
property: property
});
};
$.fn.cssAfter = function(argument, property) {
return setPseudoElement({
elements: this,
pseudoElement: 'after',
argument: argument,
property: property
});
};
})();
$(function() {
$('.element').cssBefore('content', '"New before!"');
});
.element {
width: 480px;
margin: 0 auto;
border: 2px solid red;
}
.element::before {
content: 'Old before!';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="element"></div>
jQuery.cssの通常の関数と同様に、値を指定する必要があります
さらに、jQuery.cssの通常の関数のように、疑似要素パラメーターの値を取得することもできます。
console.log( $(element).cssBefore(parameter) );
JS:
(function() {
document.pseudoElements = {
length: 0
};
var setPseudoElement = function(parameters) {
if (typeof parameters.argument === 'object' || (parameters.argument !== undefined && parameters.property !== undefined)) {
if (!parameters.element.pseudoElements) parameters.element.pseudoElements = {
styleSheet: null,
before: {
index: null,
properties: null
},
after: {
index: null,
properties: null
},
id: null
};
var selector = (function() {
if (parameters.element.pseudoElements.id !== null) {
if (Number(parameters.element.getAttribute('data-pe--id')) !== parameters.element.pseudoElements.id) parameters.element.setAttribute('data-pe--id', parameters.element.pseudoElements.id);
return '[data-pe--id="' + parameters.element.pseudoElements.id + '"]::' + parameters.pseudoElement;
} else {
var id = document.pseudoElements.length;
document.pseudoElements.length++
parameters.element.pseudoElements.id = id;
parameters.element.setAttribute('data-pe--id', id);
return '[data-pe--id="' + id + '"]::' + parameters.pseudoElement;
};
})();
if (!parameters.element.pseudoElements.styleSheet) {
if (document.styleSheets[0]) {
parameters.element.pseudoElements.styleSheet = document.styleSheets[0];
} else {
var styleSheet = document.createElement('style');
document.head.appendChild(styleSheet);
parameters.element.pseudoElements.styleSheet = styleSheet.sheet;
};
};
if (parameters.element.pseudoElements[parameters.pseudoElement].properties && parameters.element.pseudoElements[parameters.pseudoElement].index) {
parameters.element.pseudoElements.styleSheet.deleteRule(parameters.element.pseudoElements[parameters.pseudoElement].index);
};
if (typeof parameters.argument === 'object') {
parameters.argument = (function() {
var cloneObject = typeof parameters.argument.pop === 'function' ? [] : {};
for (var property in parameters.argument) {
cloneObject[property] = parameters.argument[property];
};
return cloneObject;
})();
if (!parameters.element.pseudoElements[parameters.pseudoElement].properties && !parameters.element.pseudoElements[parameters.pseudoElement].index) {
var newIndex = parameters.element.pseudoElements.styleSheet.rules.length || parameters.element.pseudoElements.styleSheet.cssRules.length || parameters.element.pseudoElements.styleSheet.length;
parameters.element.pseudoElements[parameters.pseudoElement].index = newIndex;
parameters.element.pseudoElements[parameters.pseudoElement].properties = parameters.argument;
};
var properties = '';
for (var property in parameters.argument) {
if (typeof parameters.argument[property] === 'function')
parameters.element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property]();
else
parameters.element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property];
};
for (var property in parameters.element.pseudoElements[parameters.pseudoElement].properties) {
properties += property + ': ' + parameters.element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';
};
parameters.element.pseudoElements.styleSheet.addRule(selector, properties, parameters.element.pseudoElements[parameters.pseudoElement].index);
} else if (parameters.argument !== undefined && parameters.property !== undefined) {
if (!parameters.element.pseudoElements[parameters.pseudoElement].properties && !parameters.element.pseudoElements[parameters.pseudoElement].index) {
var newIndex = parameters.element.pseudoElements.styleSheet.rules.length || parameters.element.pseudoElements.styleSheet.cssRules.length || parameters.element.pseudoElements.styleSheet.length;
parameters.element.pseudoElements[parameters.pseudoElement].index = newIndex;
parameters.element.pseudoElements[parameters.pseudoElement].properties = {};
};
if (typeof parameters.property === 'function')
parameters.element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property();
else
parameters.element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property;
var properties = '';
for (var property in parameters.element.pseudoElements[parameters.pseudoElement].properties) {
properties += property + ': ' + parameters.element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';
};
parameters.element.pseudoElements.styleSheet.addRule(selector, properties, parameters.element.pseudoElements[parameters.pseudoElement].index);
};
} else if (parameters.argument !== undefined && parameters.property === undefined) {
var windowStyle = window.getComputedStyle(
parameters.element, '::' + parameters.pseudoElement
).getPropertyValue(parameters.argument);
if (parameters.element.pseudoElements) {
return parameters.element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] || windowStyle;
} else {
return windowStyle || null;
};
} else {
console.error('Invalid values!');
return false;
};
};
Object.defineProperty(Element.prototype, 'styleBefore', {
enumerable: false,
value: function(argument, property) {
return setPseudoElement({
element: this,
pseudoElement: 'before',
argument: argument,
property: property
});
}
});
Object.defineProperty(Element.prototype, 'styleAfter', {
enumerable: false,
value: function(argument, property) {
return setPseudoElement({
element: this,
pseudoElement: 'after',
argument: argument,
property: property
});
}
});
})();
document.querySelector('.element').styleBefore('content', '"New before!"');
.element {
width: 480px;
margin: 0 auto;
border: 2px solid red;
}
.element::before {
content: 'Old before!';
}
<div class="element"></div>
GitHub:https ://github.com/yuri-spivak/managing-the-properties-of-pseudo-elements/
.css()
特定の要素に使用するようなcss-pseudoルールを追加するjQueryプラグインを作成しました。
利用方法:
$('body')
.css({
backgroundColor: 'white'
})
.cssPseudo('after', {
content: 'attr(title) ", you should try to hover the picture, then click it."',
position: 'absolute',
top: 20, left: 20
})
.cssPseudo('hover:after', {
content: '"Now hover the picture, then click it!"'
});
$('.span').attr('data-txt', 'foo');
$('.span').click(function () {
$(this).attr('data-txt',"any other text");
})
.span{
}
.span:after{
content: attr(data-txt);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='span'></div>
他の誰かが、フルスタイル要素を使用してhead要素に追加することについてコメントしました。これは、1回だけ実行する場合は悪くありませんが、複数回リセットする必要がある場合は、大量のスタイル要素になります。したがって、これを防ぐために、頭に空白のスタイル要素をIDで作成し、そのinnerHTMLを次のように置き換えます。
<style id="pseudo"></style>
その場合、JavaScriptは次のようになります。
var pseudo = document.getElementById("pseudo");
function setHeight() {
let height = document.getElementById("container").clientHeight;
pseudo.innerHTML = `.class:before { height: ${height}px; }`
}
setHeight()
私の場合、別の要素の高さに基づいてbefore要素の高さを設定するためにこれが必要でした。サイズ変更時に変更されるため、これを使用するとsetHeight()
、ウィンドウのサイズが変更されるたびに実行でき、<style>
適切に置き換えられます。
それが同じことをしようとして立ち往生している誰かを助けることを願っています。
:root
内部で定義された変数を使用しCSS
て:after
(同じことが:before
)疑似要素を変更しました。特に、JavaScriptを使用してランダムな色を生成する次のデモで、によって定義されbackground-color
たスタイルの値と別の( )の値を変更しました。 / jQuery:anchor
.sliding-middle-out:hover:after
content
anchor
#reference
HTML
<a href="#" id="changeColor" class="sliding-middle-out" title="Generate a random color">Change link color</a>
<span id="log"></span>
<h6>
<a href="https://stackoverflow.com/a/52360188/2149425" id="reference" class="sliding-middle-out" target="_blank" title="Stack Overflow topic">Reference</a>
</h6>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/davidmerfield/randomColor/master/randomColor.js"></script>
CSS
:root {
--anchorsFg: #0DAFA4;
}
a, a:visited, a:focus, a:active {
text-decoration: none;
color: var(--anchorsFg);
outline: 0;
font-style: italic;
-webkit-transition: color 250ms ease-in-out;
-moz-transition: color 250ms ease-in-out;
-ms-transition: color 250ms ease-in-out;
-o-transition: color 250ms ease-in-out;
transition: color 250ms ease-in-out;
}
.sliding-middle-out {
display: inline-block;
position: relative;
padding-bottom: 1px;
}
.sliding-middle-out:after {
content: '';
display: block;
margin: auto;
height: 1px;
width: 0px;
background-color: transparent;
-webkit-transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
-moz-transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
-ms-transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
-o-transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
}
.sliding-middle-out:hover:after {
width: 100%;
background-color: var(--anchorsFg);
outline: 0;
}
#reference {
margin-top: 20px;
}
.sliding-middle-out:before {
content: attr(data-content);
display: attr(data-display);
}
JS / jQuery
var anchorsFg = randomColor();
$( ".sliding-middle-out" ).hover(function(){
$( ":root" ).css({"--anchorsFg" : anchorsFg});
});
$( "#reference" ).hover(
function(){
$(this).attr("data-content", "Hello World!").attr("data-display", "block").html("");
},
function(){
$(this).attr("data-content", "Reference").attr("data-display", "inline").html("");
}
);
初めて私が自分自身を与える前に与えられたすべての答えを読んでいないので、これが私を噛まないことを願っています...
a
私の場合、これはに付けられたアイコンdiv
とbutton
要素に必要でしたが、それ以降とは少し動作が異なり、クラス<i class="icon-class"></i>
はありませんでした。しかし、壊れたスタイリングicon-class
を追加します。class="icon-class"
data-icon
代わりに、想定されていた値を使用して属性を追加しelement::before { content: "HERE" }
、このかなり単純なJavaScriptが残りを処理しました。
{
const fakeIcons = document.querySelectorAll('[data-icon]')
for (const iconElement of fakeIcons) {
const fakeClass = 'fake-' + Array.from(Array(20), () => Math.floor(Math.random() * 36).toString(36)).join('')
const beforeContent = iconElement.getAttribute('data-icon')
iconElement.classList.add(fakeClass)
const style = document.createElement('style')
style.type = 'text/css'
style.innerHTML = `
.${fakeClass}::before {
content: "${beforeContent}" !important;
}
`
document.getElementsByTagName('head')[0].appendChild(style)
}
}
コードの説明:
data-icon
)fake-
、その後にランダムな英数字の文字列が続くクラス名をランダムに生成しますdata-icon
属性の値を取得する::before
以前にフェッチした値にコンテンツを設定する疑似要素のスタイルを作成します<head>
HTML要素の最後にスタイルを追加します以下の解決策は、 javascriptattr属性を使用して疑似要素を更新する方法を示しています。
setAttributeを使用してjavascriptで操作できる属性をHTMLに追加します。
<div
id="inputBoxParent"
count="0">
...
</div>
jsで更新
inputBoxParent.setAttribute('count', value.length)
CSS-疑似要素でattr(attributeName)としてコンテンツを追加します
.input-box-container::after{
content: attr(count);
}
そして、あなたは終わりました!!!
const inputBoxParent = document.getElementById("inputBoxParent");
const handleOnChange = (value) => {
inputBoxParent.setAttribute('count', value.length)
}
.input-box-container {
position: relative;
width: 200px;
}
.input-box-container::after{
position: absolute;
bottom: 8px;
right: 10px;
height: 10px;
width: 20px;
content: attr(count);
}
<h4> Type some text inside the box and click outside to see resule i.e. pseudo element content change</h4>
<div
id="inputBoxParent"
class="input-box-container"
count="0">
<input
type="text"
id="inputBox"
placeholder="type some thing"
onchange="handleOnChange(this.value)"
onkeyup="handleOnChange(this.value)"
/>
</div>
私はあなたのために簡単で効果的な何か違うものを持っています。
<style>
.case-after:after { // set your properties here like eg:
color:#3fd309 !important;
}
.case-before:before { // set your properties here like eg:
color:#151715 !important;
}
</style>
// case for after
$('#button-id').on('click', function() {
$(".target-div").toggleClass('case-after');
});
// case for before
$('#button-id').on('click', function() {
$(".target-div").toggleClass('case-before');
});
継承のスタイルを持つように前または後に疑似を設定してから、javascriptを使用して親スタイルを設定します。
たとえば、:beforeのカラースタイルを変更したい場合は、:を設定します。
.my-style::before{
color: inherit;
}
次に、javascriptを使用して.my-style要素のカラースタイルを変更します。
document.querySelector(".my-style").style.color = red;
仕事は終わった、超シンプル