[英]Modify CSS selector :after with JavaScript
How do I access or modify pseudo-selectors like :after and :hover of CSS of an element through JavaScript (please no jQuery). 如何通过JavaScript访问或修改元素CSS的伪选择器,如:after和:hover (请不要使用jQuery)。
Example 例
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Progress bar example</title>
<style type="text/css">
.progressbar
{
position: relative;
width: 100px;
height: 10px;
background-color: red;
}
.progressbar:after
{
content: "";
position: absolute;
width: 25%;
height: 100%;
background-color: blue;
}
</style>
</head>
<body>
<div id="progressbar" class="progressbar" onclick="this.style.width='90%';"></div>
</body>
</html>
Like you see I want to use somethink like a progress bar, so I can't simply exchange/add/remove a second class to an element. 就像您看到的那样,我想使用进度条之类的东西,所以我不能简单地将第二个类交换/添加/删除到元素。 I would like to access the the width property of the progressbar:after (with the :after selector) class directly through JS.
我想直接通过JS访问progressbar:after (使用:after选择器)类的width属性。 But how?
但是如何?
You could give this a try: 您可以尝试一下:
EDITED EDITED
//create new style element
var style = document.createElement("style");
//append the style
document.head.appendChild(style);
//take the stylesheet object
sheet = style.sheet
//add the rule to your stylesheet -- changed this line to .insertRule
sheet.insertRule('.progressbar::after { width: 50% }', 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.