更改样式:before和:after伪元素? [英] Change the style of :before and :after pseudo-elements?

查看:956
本文介绍了更改样式:before和:after伪元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码看起来像:

This is what my code looks like:

$('.mainSpan:before').css('background','url(_gfx/cmn/main_bg.png)');

这似乎不工作,所以我问是否甚至可能添加

This does not seem to work so I'm asking if it's even possible to add background images to shadow elements with jQuery.

推荐答案

使用Javascript不能直接访问伪元素,因为它们不是部分的DOM。您可以使用可选的第二个参数()查看其样式,其中大多数(尽管并非所有)当前使用的浏览器都支持 - 在 .getComputedStyle()

It's not possible to directly access pseudo-elements with Javascript as they're not part of the DOM. You can read their style using the optional second argument - which most, although not all, browsers in current use support - in .getComputedStyle() but you can't directly change their style.

但是,您可以通过添加一个新的来间接改变他们的风格, style 元素包含新规则。例如:

However, you could change their style indirectly by adding in a new style element containing new rules. For example:

http://jsfiddle.net/sjFML /

初始CSS分配具有绿色背景的:before 伪元素,通过插入新的样式元素变成黑色。

The initial CSS assigns the :before pseudo-element with a green background, which is turned to black by inserting a new style element.

HTML:

<div id="theDiv"></div>

CSS:

#theDiv {
    height: 100px;
    background: red;
}

#theDiv:before {
    content:' ';
    display: block;
    width: 50px;
    height: 50px;
    background: green;
}

Javascript:

Javascript:

var styleElem = document.head.appendChild(document.createElement("style"));

styleElem.innerHTML = "#theDiv:before {background: black;}";

这篇关于更改样式:before和:after伪元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆