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

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

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

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


当前回答

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

其他回答

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

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

谢谢大家! 我设法做了我想做的事: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>

在jQuery中不能选择伪元素,因为它们不是DOM的一部分。 但是你可以在父元素中添加一个特定的类,并在CSS中控制它的伪元素。

例子

jQuery:

<script type="text/javascript">
    $('span').addClass('change');
</script>

在CSS中:

span.change:after { content: 'bar' }

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

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的具体值。

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

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

阿达什·赫格德。

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

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

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

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