如何通过 JavaScript 更改伪类样式?
为了简单起见,这个例子只是说明我需要做什么。 假设我有一个元素,其样式是在 CSS 中设置的。样式是为元素和伪类设置的,例如 element:hover。我可以使用以下 JavaScript 覆盖元素的样式: element.style.setProperty('属性名称', '新值', ''). 如何通过 JavaScript 更改伪类的样式?
谢谢。
<html>
<head>
<style type='text/css'>
#myBtn {
background-color: red;
}
#myBtn:hover {
background-color: blue;
}
</style>
</head>
<body>
<button id='myBtn'>Colored button</button>
<button onclick="ChangeColor();">Script button</button>
<script type="application/x-javascript">
function ChangeColor() {
var Btn = document.getElementById('myBtn');
Btn.style.setProperty('background-color', 'green', '');
};
</script>
</body>
</html>
This example is, for a matter of simplicity, just an illustration of what I need to do.
Say, I have an element, which style is set in a CSS. The style is set for the element as well as for a Pseudo-class, say element:hover. I can override the style for the element with the following JavaScript:
element.style.setProperty('property-name', 'new value', '').
How can I change the Pseudo-class's style through JavaScript?
Thank you.
<html>
<head>
<style type='text/css'>
#myBtn {
background-color: red;
}
#myBtn:hover {
background-color: blue;
}
</style>
</head>
<body>
<button id='myBtn'>Colored button</button>
<button onclick="ChangeColor();">Script button</button>
<script type="application/x-javascript">
function ChangeColor() {
var Btn = document.getElementById('myBtn');
Btn.style.setProperty('background-color', 'green', '');
};
</script>
</body>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会使用一组不同的规则和一个附加类
,然后
当然,这仅对您想要的颜色的一个或几个不同值有意义。
I would use a different set of rules with an additional class
And then
Of course, this makes only sense for one or a couple of different values you want to have for your color.
CSS 伪类和伪元素不是 DOM 的一部分,因此您无法直接使用 JavaScript 修改它们的样式属性。
某些动态伪类(例如
:hover
)可能具有类似的 JavaScript 事件 (onmouseover onmouseout
),您可以使用它们来更改样式,但这并不意味着之间存在实际关联两个。CSS pseudo-classes and pseudo-elements are not part of the DOM, and thus you cannot modify their style properties directly using JavaScript.
Certain dynamic pseudo-classes like
:hover
may have similar JavaScript events (onmouseover onmouseout
) that you can use to change styles, but this doesn't mean there's an actual correlation between the two.您不能直接修改它们,但可以将 CSS 插入到 DOM 的头部。
You can't modify them directly but you can insert the CSS to the head portion of the DOM.
您可以修改 IE6+ 和大多数其他浏览器中的现有样式表。
编辑现有规则是可能的,但跨浏览器很棘手。
此示例将新规则(选择器和声明)添加到文档中的最后一个样式表。
You can tinker with existing stylesheets in IE6+ and most of the other browsers.
Editing existing rules is possible, but tricky cross-browser.
This example adds a new rule (selector and declaration) to the last stylesheet in the document.