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

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

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

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


当前回答

为什么要添加类或属性,当你可以添加一个样式头

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

其他回答

你也可以将内容传递给带有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';
}

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

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

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

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

我已经创建了一个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!"'
  });

下面是HTML:

<div class="icon">
  <span class="play">
    ::before
  </span>
</div>

“before”上的计算样式是内容:“VERIFY TO WATCH”;

下面是我的两行jQuery代码,它们使用了添加一个额外的类来特别引用这个元素,然后附加一个样式标签(带一个!important标签)来改变sudo元素内容值的CSS:

$(“span.play:eq(0)”).addClass('G');

$('体').append(“<时尚>。G:在{重要内容:“NewText”!}> < /风格”);