有什么方法来选择/操作CSS伪元素,如::before和::after(和旧版本的一个分号)使用jQuery?

例如,我的样式表有以下规则:

.span::after{ content:'foo' }

我怎么能改变'foo'到'酒吧'使用香草JS或jQuery?


当前回答

我们还可以依赖自定义属性(即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自定义属性(变量)框模型

其他回答

你也可以将内容传递给带有data属性的伪元素,然后使用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';
}

我在CSS中使用:root中定义的变量来修改:after(同样适用于:before)伪元素,特别是在下面使用JavaScript/jQuery生成随机颜色的演示中,更改由. slide -middle-out:hover:after定义的样式锚的背景颜色值和另一个锚(#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("");
 }
);

尽管它们是由浏览器通过CSS呈现的,就像它们像其他真正的DOM元素一样,但伪元素本身不是DOM的一部分,因为伪元素,顾名思义,不是真正的元素,因此您不能直接使用jQuery(或任何JavaScript API,甚至是Selectors API)选择和操作它们。这适用于您试图用脚本修改其样式的任何伪元素,而不仅仅是::before和::after。

你只能在运行时通过CSSOM(想想window.getComputedStyle())直接访问伪元素样式,jQuery除了.css()之外不会公开它,这个方法也不支持伪元素。

不过,你总能找到其他方法,比如:

将样式应用到一个或多个任意类的伪元素上,然后在类之间切换(参看seucolega的回答以获得一个快速示例)——这是一种惯用的方法,因为它使用简单的选择器(伪元素没有)来区分元素和元素状态,这是它们打算使用的方式 通过修改文档样式表来操纵应用于上述伪元素的样式,这更像是一种hack

这是我第一次在给出我自己的答案之前没有阅读所有给出的答案,所以我希望这不会让我…

在我的情况下,这是需要的图标附加到一个,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元素的末尾添加样式

您可能认为这是一个很简单的问题,使用jQuery可以做的所有其他事情。不幸的是,这个问题归结为一个技术问题:css:after和:before规则不是DOM的一部分,因此不能使用jQuery的DOM方法进行修改。

有一些方法可以使用JavaScript和/或CSS工作区来操作这些元素;您使用哪一种取决于您的确切需求。


我将从被广泛认为是“最佳”的方法开始:

1)添加/删除一个预定的类

在这种方法中,您已经在CSS中创建了一个具有不同的:after或:before样式的类。将这个“new”类放在样式表的后面,以确保它被覆盖:

p:before {
    content: "foo";
}
p.special:before {
    content: "bar";
}

然后你可以很容易地添加或删除这个类使用jQuery(或香草JavaScript):

$('p').on('click', function() {
    $(this).toggleClass('special');
});

美元(“p”)。On('点击',函数(){ (美元).toggleClass(特殊的); }); p:{之前 内容:“foo”; 颜色:红色; 光标:指针; } p.special:{之前 内容:“酒吧”; } < script src = " https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js " > < /脚本> <p>这是一个段落 <p>这是另一段

优点:易于实现与jQuery;快速改变多个风格在一次;强制分离关注点(从HTML中隔离CSS和JS) 缺点:CSS必须预先编写,因此:before或:after的内容不是完全动态的


2)直接在文档的样式表中添加新样式

可以使用JavaScript直接向文档样式表添加样式,包括:after和:before样式。jQuery并没有提供方便的快捷方式,但幸运的是JS并没有那么复杂:

var str = "bar";
document.styleSheets[0].addRule('p.special:before','content: "'+str+'";');

Var STR = "bar"; document.styleSheets [0] .addRule(“p。特殊:在` `之前,` `内容:` ` + STR + ` ` ` ` ` `); p:{之前 内容:“foo”; 颜色:红色; } < script src = " https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js " > < /脚本> <p class="special">这是一个段落</p> 这是另一段</p>

. addrule()和相关的. insertrule()方法目前得到了很好的支持。

作为一种变体,你也可以使用jQuery来添加一个全新的样式表到文档中,但必要的代码并不干净:

var str = "bar";
$('<style>p.special:before{content:"'+str+'"}</style>').appendTo('head');

Var STR = "bar"; $(' <时尚> p。特殊:{之前内容:“+ str +”}> < /风格”).appendTo(头); p:{之前 内容:“foo”; 颜色:红色; } < script src = " https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js " > < /脚本> <p class="special">这是一个段落</p> 这是另一段</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。特殊:before', 'content: "' +str +str + '";'); p:{之前 内容:“foo”; 颜色:红色; } < script src = " https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js " > < /脚本> <p class="special">这是一个段落</p> 这是另一段</p>

在使用jQuery时,我们可以将document.querySelector('p')替换为$('p')[0],以获得稍短的代码。

优点:任何字符串都可以动态插入到样式中 缺点:原始样式不会被改变,只是被覆盖;重复使用(ab)可以使DOM变得任意大


3)改变一个不同的DOM属性

您还可以在CSS中使用attr()来读取特定的DOM属性。(如果浏览器支持:before,它也支持attr())在一些精心准备的CSS中,通过将此与content:结合起来,我们可以动态地更改:before和:after的内容(但不能更改其他属性,如边距或颜色):

p:before {
    content: attr(data-before);
    color: red;
    cursor: pointer;
}

JS:

$('p').on('click', function () {
    $(this).attr('data-before','bar');
});

美元(“p”)。On('点击',函数(){ (美元).attr(“数据”、“酒吧”); }); p:{之前 内容:attr(数据); 颜色:红色; 光标:指针; } < script src = " https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js " > < /脚本> <p>这是一个段落 <p>这是另一段

如果CSS不能提前准备,这可以与第二种技术结合使用:

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('点击',函数(){ (美元)。attr(“数据”,str); }); p:{之前 内容:“foo”; 颜色:红色; 光标:指针; } < script src = " https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js " > < /脚本> <p>这是一个段落 <p>这是另一段

优点:不会创造出无尽的额外风格 缺点:CSS中的attr只能应用于内容字符串,而不是url或RGB颜色