有什么方法来选择/操作CSS伪元素,如::before和::after(和旧版本的一个分号)使用jQuery?
例如,我的样式表有以下规则:
.span::after{ content:'foo' }
我怎么能改变'foo'到'酒吧'使用香草JS或jQuery?
有什么方法来选择/操作CSS伪元素,如::before和::after(和旧版本的一个分号)使用jQuery?
例如,我的样式表有以下规则:
.span::after{ content:'foo' }
我怎么能改变'foo'到'酒吧'使用香草JS或jQuery?
当前回答
只需要在之前或之后设置伪样式来继承,然后用javascript设置父样式。
例如,我想改变:before的颜色样式,然后我设置:
.my-style::before{
color: inherit;
}
然后我用javascript改变了.my-style元素的颜色样式:
document.querySelector(".my-style").style.color = red;
工作完成了,超级简单
其他回答
下面是访问:after和:before样式属性的方法,在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');
你可以使用我的插件来实现这个目的。
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的普通函数中一样
此外,你还可以获得pseudo-element参数的值,就像在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和按钮元素,这与<i class="icon-class"></i>的工作有点不同,因为他们没有icon-class类。添加class="icon-class"会破坏样式。
相反,我为它们添加了一个数据图标属性,其中的值应该在element:: {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属性的值 向元素中添加随机生成的类 在伪元素设置内容之前为::创建样式 在<head> HTML元素的末尾添加样式
您可以创建一个伪属性,也可以使用一个现有的属性,并在伪元素的样式表中继承它。
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变量)来操作伪元素。我们可以在规范中读到:
自定义属性是普通属性,因此可以在 任何元素,都用正常的继承和级联进行解析 规则,可以使用@media等条件规则,可以在HTML的样式属性中使用,可以使用CSSOM读取或设置等。
考虑到这一点,我们的想法是在元素中定义自定义属性,伪元素将简单地继承它;因此,我们可以很容易地修改它。
1)使用内联样式:
.box:{之前 content:var(——content,“我是一个before元素”); 颜色:var(——颜色、红色); 字体大小:25 px; } < div class = "盒子" > < / div > <div class="box" style="——color:blue;——content:'I am a blue element'"></div> <div class="box" style="——color:黑色"></div> . <div class="box" style="——color:#f0f;——content:'another element'"></div>
2)使用CSS和类
.box:{之前 content:var(——content,“我是一个before元素”); 颜色:var(——颜色、红色); 字体大小:25 px; } .blue { ——颜色:蓝色; ——内容:“我是蓝色元素”; } {布莱克 -颜色:黑色; } < div class = "盒子" > < / div > <div class="box black" ></div> <div class="box blue"></div>
3)使用javascript
document.querySelectorAll (.box) [0] .style。setProperty(”——颜色”、“蓝色”); document.querySelectorAll (.box) [1] .style。setProperty("——content", "'我是另一个元素'"); .box:{之前 content:var(——content,“我是一个before元素”); 颜色:var(——颜色、红色); 字体大小:25 px; } < div class = "盒子" > < / div > < div class = "盒子" > < / 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:“内容”; ——b:线性渐变(红、蓝); ——年代:20 px; ——p: 0 15 px; } .box:{之前 内容:var (- c); 背景:var (- b); 颜色:# fff; Font-size: calc(2 * var(- s) + 5px); 填充:var (- p); } < div class = "盒子" > < / div >
您可能注意到,我正在考虑var(——c,value)语法,其中value是默认值,也称为回退值。
从同一规格中,我们可以读到:
一个自定义属性的值可以用var()函数替换为另一个属性的值。var()的语法是:
Var () = Var (<custom-property-name> [, <declaration-value>]?)
函数的第一个参数是要替换的自定义属性的名称。如果提供了该函数的第二个参数,则是一个回退值,当引用的自定义属性无效时,将其用作替换值。
后来:
在属性值中替换var():
If the custom property named by the first argument to the var() function is animation-tainted, and the var() function is being used in the animation property or one of its longhands, treat the custom property as having its initial value for the rest of this algorithm. If the value of the custom property named by the first argument to the var() function is anything but the initial value, replace the var() function by the value of the corresponding custom property. Otherwise, if the var() function has a fallback value as its second argument, replace the var() function by the fallback value. If there are any var() references in the fallback, substitute them as well. Otherwise, the property containing the var() function is invalid at computed-value time.
如果我们不设置自定义属性,或者我们将其设置为初始值,或者它包含一个无效值,那么将使用回退值。如果我们想将自定义属性重置为默认值,使用initial会很有帮助。
相关的
如何存储继承值内的CSS变量(又称自定义属性)?
CSS自定义属性(变量)框模型