使用 JavaScript 更改 :hover CSS 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11371550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change :hover CSS properties with JavaScript
提问by sissypants
I need to find a way to change CSS :hover properties using JavaScript.
我需要找到一种方法来使用 JavaScript 更改 CSS :hover 属性。
For example, suppose I have this HTML code:
例如,假设我有这个 HTML 代码:
<table>
<tr>
<td>Hover 1</td>
<td>Hover 2</td>
</tr>
</table>
And the following CSS code:
以及以下 CSS 代码:
table td:hover {
background:#ff0000;
}
I would like to use JavaScript to change the <td> hover properties to, say, background:#00ff00. know I could access the style background property using JavaScript as:
我想使用 JavaScript 将 <td> 悬停属性更改为 background:#00ff00。知道我可以使用 JavaScript 访问样式背景属性:
document.getElementsByTagName("td").style.background="#00ff00";
But I don't know of a JavaScript equivalent for :hover. How do I change these <td>'s :hover background using JavaScript?
但我不知道 :hover 的 JavaScript 等价物。如何使用 JavaScript 更改这些 <td> 的 :hover 背景?
Your help is greatly appreciated!
非常感谢您的帮助!
回答by kennebec
Pseudo classes like :hover
never refer to an element, but to any element that satisfies the conditions of the stylesheet rule. You need to edit the stylesheet rule, append a new rule, or add a new stylesheet that includes the new :hover
rule.
伪类:hover
永远不会引用元素,而是引用任何满足样式表规则条件的元素。您需要编辑样式表规则、附加新规则或添加包含新:hover
规则的新样式表。
var css = 'table td:hover{ background-color: #00ff00 }';
var style = document.createElement('style');
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
document.getElementsByTagName('head')[0].appendChild(style);
回答by Achal Dave
You can'tchange or alter the actual :hover
selector through Javascript. You can, however, use mouseenter
to change the style, and revert back on mouseleave
(thanks, @Bryan).
您无法:hover
通过 Javascript更改或更改实际选择器。但是,您可以使用mouseenter
更改样式,然后恢复mouseleave
(谢谢,@Bryan)。
回答by isgoed
What you can do is change the class of your object and define two classes with different hover properties. For example:
您可以做的是更改对象的类并定义两个具有不同悬停属性的类。例如:
.stategood_enabled:hover { background-color:green}
.stategood_enabled { background-color:black}
.stategood_disabled:hover { background-color:red}
.stategood_disabled { background-color:black}
And this I found on: Change an element's class with JavaScript
这是我发现的: 用 JavaScript 更改元素的类
function changeClass(object,oldClass,newClass)
{
// remove:
//object.className = object.className.replace( /(?:^|\s)oldClass(?!\S)/g , '' );
// replace:
var regExp = new RegExp('(?:^|\s)' + oldClass + '(?!\S)', 'g');
object.className = object.className.replace( regExp , newClass );
// add
//object.className += " "+newClass;
}
changeClass(myInput.submit,"stategood_disabled"," stategood_enabled");
回答by David Spector
Sorry to find this page 7 years too late, but here is a much simpler way to solve this problem (changing hover styles arbitrarily):
很抱歉找到这个页面已经晚了 7 年,但这里有一个更简单的方法来解决这个问题(任意更改悬停样式):
HTML:
HTML:
<button id=Button>Button Title</button>
CSS:
CSS:
.HoverClass1:hover {color: blue !important; background-color: green !important;}
.HoverClass2:hover {color: red !important; background-color: yellow !important;}
JavaScript:
JavaScript:
var Button=document.getElementById('Button');
/* Clear all previous hover classes */
Button.classList.remove('HoverClass1','HoverClass2');
/* Set the desired hover class */
Button.classList.add('HoverClass1');
回答by Namit Juneja
If it fits your purpose you can add the hover functionality without using css and using the onmouseover
event in javascript
如果它符合您的目的,您可以在不使用 css 和onmouseover
在 javascript 中使用事件的情况下添加悬停功能
Here is a code snippet
这是一个代码片段
<div id="mydiv">foo</div>
<script>
document.getElementById("mydiv").onmouseover = function()
{
this.style.backgroundColor = "blue";
}
</script>
回答by ybentz
Pretty old question so I figured I'll add a more modern answer. Now that CSS variables are widely supported they can be used to achieve this without the need for JS events or !important
.
很老的问题,所以我想我会添加一个更现代的答案。现在 CSS 变量得到了广泛的支持,它们可以用来实现这一点,而无需 JS 事件或!important
.
Taking the OP's example:
以 OP 为例:
<table>
<tr>
<td>Hover 1</td>
<td>Hover 2</td>
</tr>
</table>
We can now do this in the CSS:
我们现在可以在 CSS 中做到这一点:
table td:hover {
// fallback in case we need to support older/non-supported browsers (IE, Opera mini)
background: #ff0000;
background: var(--td-background-color);
}
And add the hover state using javascript like so:
并使用 javascript 添加悬停状态,如下所示:
const tds = document.querySelectorAll('td');
tds.forEach((td) => {
td.style.setProperty('--td-background-color', '#00ff00');
});
Here's a working example https://codepen.io/ybentz/pen/RwPoeqb
回答by elPastor
This is not actually adding the CSS to the cell, but gives the same effect. While providing the same result as others above, this version is a little more intuitive to me, but I'm a novice, so take it for what it's worth:
这实际上并不是将 CSS 添加到单元格中,而是提供了相同的效果。虽然提供与上面其他版本相同的结果,但这个版本对我来说更直观一些,但我是新手,所以它的价值在于:
$(".hoverCell").bind('mouseover', function() {
var old_color = $(this).css("background-color");
$(this)[0].style.backgroundColor = '#ffff00';
$(".hoverCell").bind('mouseout', function () {
$(this)[0].style.backgroundColor = old_color;
});
});
This requires setting the Class for each of the cells you want to highlight to "hoverCell".
这需要将要突出显示的每个单元格的类设置为“hoverCell”。
回答by Tero Tolonen
I had this need once and created a small library for, which maintains the CSS documents
我曾经有过这个需求,并为其创建了一个小型库,用于维护 CSS 文档
https://github.com/terotests/css
https://github.com/terotests/css
With that you can state
有了它你可以说
css().bind("TD:hover", {
"background" : "00ff00"
});
It uses the techniques mentioned above and also tries to take care of the cross-browser issues. If there for some reason exists an old browser like IE9 it will limit the number of STYLE tags, because the older IE browser had this strange limit for number of STYLE tags available on the page.
它使用上面提到的技术,并试图解决跨浏览器的问题。如果由于某种原因存在像 IE9 这样的旧浏览器,它将限制 STYLE 标签的数量,因为旧版 IE 浏览器对页面上可用的 STYLE 标签数量有这种奇怪的限制。
Also, it limits the traffic to the tags by updating tags only periodically. There is also a limited support for creating animation classes.
此外,它通过仅定期更新标签来限制到标签的流量。对创建动画类的支持也很有限。
回答by Shobhit Sharma
I'd recommend to replace all :hover
properties to :active
when you detect that device supports touch. Just call this function when you do so as touch()
当您检测到该设备支持触摸时,我建议将所有:hover
属性替换为:active
。这样做时只需调用此函数touch()
function touch() {
if ('ontouchstart' in document.documentElement) {
for (var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
var sheet = document.styleSheets[sheetI];
if (sheet.cssRules) {
for (var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
var rule = sheet.cssRules[ruleI];
if (rule.selectorText) {
rule.selectorText = rule.selectorText.replace(':hover', ':active');
}
}
}
}
}
}
回答by Gabriel Barberini
Declare a global var:
声明一个全局变量:
var td
Then select your guiena pig <td>
getting it by its id
, if you want to change all of them then
然后选择您guiena猪<td>
由其得到它id
,如果你想改变所有这些,然后
window.onload = function () {
td = document.getElementsByTagName("td");
}
Make a function to be triggered and a loop to change all of your desired td
's
制作一个被触发的函数和一个循环来改变你想要td
的所有
function trigger() {
for(var x = 0; x < td.length; x++) {
td[x].className = "yournewclass";
}
}
Go to your CSS Sheet:
转到您的 CSS 表:
.yournewclass:hover { background-color: #00ff00; }
And that is it, with this you are able to to make all your <td>
tags get a background-color: #00ff00;
when hovered by changing its css propriety directly (switching between css classes).
就是这样,通过直接更改其 css 属性(在 css 类之间切换),您可以使所有<td>
标签background-color: #00ff00;
在悬停时获得一个。