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

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

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

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


当前回答

我在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("");
 }
);

其他回答

下面是访问: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');

谢谢大家! 我设法做了我想做的事:D http://jsfiddle.net/Tfc9j/42/ 让我们来看看

我想有一个外部div的不透明度是不同于内部div的不透明度和改变点击somwewhere;) 谢谢!

   $('#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>

有人评论说附加一个完整的样式元素到头部元素,如果你只做一次,这还不错,但如果你需要重置它不止一次,你最终会有大量的样式元素。所以为了防止这种情况,我在头部创建了一个带有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>。

希望这能帮助那些被困在做同样事情的人。

您可能认为这是一个很简单的问题,使用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颜色

我在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("");
 }
);