有什么方法来选择/操作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自定义属性(变量)框模型

其他回答

这是不实际的,因为我没有为现实世界的使用写这篇文章,只是给你一个可以实现的例子。

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

这个当前add's a /或追加一个Style元素,其中包含你的必要属性,这将影响目标元素的伪元素之后。

这可以用作

css.after("someElement"," content: 'Test'; position: 'absolute'; ") // editing / adding styles to :after

and

css.before( ... ); // to affect the before pseudo element.

伪元素不能直接通过DOM访问,目前不可能自由编辑css的具体值。

我的方法只是一个例子,它不适合练习,你可以修改它,尝试一些你自己的技巧,使它适合真实世界的使用。

所以用这个和其他东西做你自己的实验吧!

阿达什·赫格德。

我有一些不同的东西给你,既简单又有效。

    <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');
    });

这里有很多答案,但没有一个答案有助于操作:before或:after的css,甚至不是公认的答案。

以下是我的建议。让我们假设你的HTML是这样的:

<div id="something">Test</div>

然后你在CSS中设置它的:before并像这样设计它:

#something:before{
   content:"1st";
   font-size:20px;
   color:red;
}
#something{
  content:'1st';
}

请注意,我还在元素本身设置了内容属性,以便稍后可以轻松取出。 现在有一个按钮点击,你想改变的颜色:before绿色和它的字体大小为30px。您可以通过以下方法实现:

在一些类.active上定义一个样式符合你要求的css:

.activeS:before{
   color:green !important;
   font-size:30px !important;
 }

现在你可以通过添加类到你的:before元素来改变:before样式,如下所示:

<button id="changeBefore">Change</button>
<script>
    $('#changeBefore').click(function(){
        $('#something').addClass('activeS');
    });
</script>

如果你只是想获取:之前的内容,可以这样做:

<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”按钮将更改:在#something的内容之前变为“22”,这是一个动态值。

我希望这对你们有帮助

我已经创建了一个jQuery插件来添加css伪规则,如使用.css()为特定的元素。

插件代码和测试用例在这里(更新的Fiddle) 用例作为简单的CSS图像弹出这里

用法:

$('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!"'
  });

根据克里斯蒂安的建议,你还可以这样做:

$('head').append("<style>.span::after{ content:'bar' }</style>");