选择和操作 CSS 伪元素,例如: : before 和: : after using jQuery
Is there any way to select/manipulate CSS pseudo-elements such as ::before
and ::after
(and the old version with one semi-colon) using jQuery?
For example, my stylesheet has the following rule:
.span::after{ content:'foo' }
How can I change 'foo' to 'bar' using jQuery?
转载于:https://stackoverflow.com/questions/5041494/selecting-and-manipulating-css-pseudo-elements-such-as-before-and-after-usin
You could also pass the content to the pseudo element with a data attribute and then use jQuery to manipulate that:
In HTML:
<span>foo</span>
In jQuery:
$('span').hover(function(){
$(this).attr('data-content','bar');
});
In CSS:
span:after {
content: attr(data-content) ' any other text you may want';
}
If you want to prevent the 'other text' from showing up, you could combine this with seucolega's solution like this:
In HTML:
<span>foo</span>
In jQuery:
$('span').hover(function(){
$(this).addClass('change').attr('data-content','bar');
});
In CSS:
span.change:after {
content: attr(data-content) ' any other text you may want';
}
Although they are rendered by browsers through CSS as if they were like other real DOM elements, pseudo-elements themselves are not part of the DOM, because pseudo-elements, as the name implies, are not real elements, and therefore you can't select and manipulate them directly with jQuery (or any JavaScript APIs for that matter, not even the Selectors API). This applies to any pseudo-elements whose styles you're trying to modify with a script, and not just ::before
and ::after
.
You can only access pseudo-element styles directly at runtime via the CSSOM (think window.getComputedStyle()
), which is not exposed by jQuery beyond .css()
, a method that doesn't support pseudo-elements either.
You can always find other ways around it, though, for example:
Applying the styles to the pseudo-elements of one or more arbitrary classes, then toggling between classes (see seucolega's answer for a quick example) — this is the idiomatic way as it makes use of simple selectors (which pseudo-elements are not) to distinguish between elements and element states, the way they're intended to be used
Manipulating the styles being applied to said pseudo-elements, by altering the document stylesheet, which is much more of a hack
You can't select pseudo elements in jQuery because they are not part of DOM. But you can add an specific class to the father element and control its pseudo elements in CSS.
In jQuery:
<script type="text/javascript">
$('span').addClass('change');
</script>
In CSS:
span.change:after { content: 'bar' }
one working but not very efficient way is to add a rule to the document with the new content and reference it with a class. depending on what is needed the class might need an unique id for each value in content.
$("<style type='text/css'>span.id-after:after{content:bar;}</style>").appendTo($("head"));
$('span').addClass('id-after');
In the line of what Christian suggests, you could also do:
$('head').append("<style>.span::after{ content:'bar' }</style>");
You'd think this would be a simple question to answer, with everything else that jQuery can do. Unfortunately, the problem comes down to a technical issue: css :after and :before rules aren't part of the DOM, and therefore can't be altered using jQuery's DOM methods.
There are ways to manipulate these elements using JavaScript and/or CSS workarounds; which one you use depends on your exact requirements.
I'm going to start with what's widely considered the "best" approach:
1) Add/remove a predetermined class
In this approach, you've already created a class in your CSS with a different :after
or :before
style. Place this "new" class later in your stylesheet to make sure it overrides:
p:before {
content: "foo";
}
p.special:before {
content: "bar";
}
Then you can easily add or remove this class using jQuery (or vanilla 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>
- Pros: Easy to implement with jQuery; quickly alters multiple styles at once; enforces separation of concerns (isolating your CSS and JS from your HTML)
-
Cons: CSS must be pre-written, so the content of
:before
or:after
isn't completely dynamic
2) Add new styles directly to the document's stylesheet
It's possible to use JavaScript to add styles directly to the document stylesheet, including :after
and :before
styles. jQuery doesn't provide a convenient shortcut, but fortunately the JS isn't that complicated:
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()
and the related .insertRule()
methods are fairly well-supported today.
As a variation, you can also use jQuery to add an entirely new stylesheet to the document, but the necessary code isn't any cleaner:
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>
If we're talking about "manipulating" the values, not just adding to them, we can also read the existing :after
or :before
styles using a different approach:
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>
We can replace document.querySelector('p')
with $('p')[0]
when using jQuery, for slightly shorter code.
- Pros: any string can be dynamically inserted into the style
- Cons: original styles aren't altered, just overridden; repeated (ab)use can make the DOM grow arbitrarily large
3) Alter a different DOM attribute
You can also to use attr()
in your CSS to read a particular DOM attribute. (If a browser supports :before
, it supports attr()
as well.) By combining this with content:
in some carefully-prepared CSS, we can change the content (but not other properties, like margin or color) of :before
and :after
dynamically:
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>
This can be combined with the second technique if the CSS can't be prepared ahead of time:
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>
- Pros: Doesn't create endless extra styles
-
Cons:
attr
in CSS can only apply to content strings, not URLs or RGB colors
</div>
Here is the HTML:
<div class="icon">
<span class="play">
::before
</span>
</div>
Computed style on 'before' was content: "VERIFY TO WATCH";
Here is my two lines of jQuery, which use the idea of adding an extra class to specifically reference this element and then appending a style tag (with an !important tag) to changes the CSS of the sudo-element's content value:
$("span.play:eq(0)").addClass('G');
$('body').append("<style>.G:before{content:'NewText' !important}</style>");
IF you want to to manipulate the ::before or ::after sudo elements entirely through CSS, you could do it JS. See below;
jQuery('head').append('<style id="mystyle" type="text/css"> /* your styles here */ </style>');
Notice how the <style>
element has an ID, which you can use to remove it and append to it again if your style changes dynamically.
This way, your element is style exactly how you want it through CSS, with the help of JS.
Thank you all! i managed to do what i wanted :D http://jsfiddle.net/Tfc9j/42/ here take a look
i wanted to have the opacity of an outer div to be different from the opacity of the internal div and that change with a click somwewhere ;) Thanks!
$('#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>
Here is the way to access :after and :before style properties, defined in css:
// 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');
You may create a fake property or use an existing one and inherit it in the pseudo-element's stylesheet.
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>
It seems it doesn't work for "content" property :(
</div>
This is not practical as i did not write this for real world uses, just to give you a example of what can be achieved.
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>");
}
}
}
this currently add's a / or appends a Style element which contains your necessary attribute's which will take affect on the target element's after Pseudo element.
this can be used as
css.after("someElement"," content: 'Test'; position: 'absolute'; ") // editing / adding styles to :after
and
css.before( ... ); // to affect the before pseudo element.
as after: and before: pseudo elements are not directly accessible through DOM it is currently not possible to edit the Specific values of the css freely.
my way was just a example and its not good for practice, you can modify it try some of your own tricks and make it correct for real world usage.
so do your own experimentation's with this and others!
regards - Adarsh Hegde.
Why adding classes or attributes when you can just append a style
to head
$('head').append('<style>.span:after{ content:'changed content' }</style>')
$('.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>
</div>
You can use my plugin for this purpose.
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>
The values should be specified, as in the normal function of jQuery.css
In addition, you can also get the value of the pseudo-element parameter, as in the normal function of 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/
</div>
Someone else commented on appending to the head element with a full style element and that's not bad if you're only doing it once but if you need to reset it more than once you'll end up with a ton of style elements. So to prevent that I created a blank style element in the head with an id and replace the innerHTML of it like this:
<style id="pseudo"></style>
Then the JavaScript would look like this:
var pseudo = document.getElementById("pseudo");
function setHeight() {
let height = document.getElementById("container").clientHeight;
pseudo.innerHTML = `.class:before { height: ${height}px; }`
}
setHeight()
Now in my case I needed this to set the height of a before element based on the height of another and it will change on resize so using this I can run setHeight()
every time the window is resized and it will replace the <style>
properly.
Hope that helps someone who was stuck trying to do the same thing.
We can also rely on CSS custom properties (variables) in order to manipulate pseudo-element. We can read in the specification that:
Custom properties are ordinary properties, so they can be declared on any element, are resolved with the normal inheritance and cascade rules, can be made conditional with @media and other conditional rules, can be used in HTML’s style attribute, can be read or set using the CSSOM, etc.
Considering this, the idea is to define the custom property within the element and the pseudo-element will simply inherit it; thus we can easily modify it.
Please note that CSS variables might not be available in all browsers you consider relevant (e.g. IE 11): https://caniuse.com/#feat=css-variables
1) Using inline style:
.box:before {
content:"I am a before element";
color:var(--color, red);
font-size:25px;
}
<div class="box"></div>
<div class="box" style="--color:blue"></div>
<div class="box" style="--color:black"></div>
<div class="box" style="--color:#f0f"></div>
2) Using CSS and classes
.box:before {
content:"I am a before element";
color:var(--color, red);
font-size:25px;
}
.blue {
--color:blue;
}
.black {
--color:black;
}
<div class="box"></div>
<div class="box black" ></div>
<div class="box blue"></div>
3) Using javascript
document.querySelectorAll('.box')[0].style.setProperty("--color", "blue");
document.querySelectorAll('.box')[1].style.setProperty("--color", "#f0f");
.box:before {
content:"I am a before element";
color:var(--color, red);
font-size:25px;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
4) Using 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>
It can also be used with complex values:
.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>
</div>
I'm always adding my own utils function, which looks like this.
function setPseudoElContent(selector, value) {
document.styleSheets[0].addRule(selector, 'content: "' + value + '";');
}
setPseudoElContent('.class::after', 'Hello World!');
or make use of ES6 Features:
const setPseudoElContent = (selector, value) => {
document.styleSheets[0].addRule(selector, `content: "${value}";`);
}
setPseudoElContent('.class::after', 'Hello World!');
I made use of variables defined in :root
inside CSS
to modify the :after
(the same applies to :before
) pseudo-element, in particular to change the background-color
value for a styled anchor
defined by .sliding-middle-out:hover:after
and the content
value for another anchor
(#reference
) in the following demo that generates random colors by using JavaScript/jQuery:
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("");
}
);