我需要找到一种方法来改变CSS:使用JavaScript悬停属性。
例如,假设我有这个HTML代码:
<table>
<tr>
<td>Hover 1</td>
<td>Hover 2</td>
</tr>
</table>
以下CSS代码:
table td:hover {
background:#ff0000;
}
我想使用JavaScript来更改&lt; td&gt;将属性悬停在背景上:#00ff00。知道我可以使用JavaScript访问样式背景属性:
document.getElementsByTagName("td").style.background="#00ff00";
但我不知道等效的JavaScript:hover。如何使用JavaScript更改这些&lt; td&gt;:悬停背景?
非常感谢您的帮助!
答案 0 :(得分:83)
像: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);
答案 1 :(得分:32)
您can't通过Javascript更改或更改实际的:hover
选择器。但是,您可以使用mouseenter
更改样式,然后恢复mouseleave
(感谢@Bryan)。
答案 2 :(得分:7)
您可以做的是更改对象的类并定义具有不同悬停属性的两个类。例如:
.stategood_enabled:hover { background-color:green}
.stategood_enabled { background-color:black}
.stategood_disabled:hover { background-color:red}
.stategood_disabled { background-color:black}
我发现这个: Change an element's class with 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");
答案 3 :(得分:4)
相当老的问题,所以我想我将添加一个更现代的答案。既然CSS变量得到了广泛的支持,它们可以用于实现此目的而无需JS事件或!important
。
以OP的示例为例:
<table>
<tr>
<td>Hover 1</td>
<td>Hover 2</td>
</tr>
</table>
我们现在可以在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);
}
并像下面这样使用javascript添加悬停状态:
const tds = document.querySelectorAll('td');
tds.forEach((td) => {
td.style.setProperty('--td-background-color', '#00ff00');
});
答案 4 :(得分:2)
如果符合您的目的,您可以添加悬停功能,而无需使用css并在javascript中使用onmouseover
事件
以下是代码段
<div id="mydiv">foo</div>
<script>
document.getElementById("mydiv").onmouseover = function()
{
this.style.backgroundColor = "blue";
}
</script>
答案 5 :(得分:1)
这实际上并不是将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;
});
});
这需要将要突出显示的每个单元格的Class设置为“hoverCell”。
答案 6 :(得分:1)
我有这个需要一次,并创建了一个小型库,用于维护CSS文档
https://github.com/terotests/css
你可以说明
css().bind("TD:hover", {
"background" : "00ff00"
});
它使用上述技术并尝试处理跨浏览器问题。如果出于某种原因存在像IE9这样的旧浏览器,它将限制STYLE标签的数量,因为较旧的IE浏览器对页面上可用的STYLE标签数量有这个奇怪的限制。
此外,它还通过定期更新标记来限制标记的流量。对创建动画类的支持也很有限。
答案 7 :(得分:1)
声明全局var:
var td
然后选择你的guiena pig <td>
通过id
获取它,如果你想改变所有这些猪那么
window.onload = function () {
td = document.getElementsByTagName("td");
}
创建一个触发函数和一个循环来更改所有想要的td
function trigger() {
for(var x = 0; x < td.length; x++) {
td[x].className = "yournewclass";
}
}
转到CSS表格:
.yournewclass:hover { background-color: #00ff00; }
就是这样,通过直接更改其css适当性(在css类之间切换),您可以通过此方式使所有<td>
标记获得background-color: #00ff00;
。
答案 8 :(得分:1)
很抱歉找到该页面已经7年了,但是这是解决此问题的一种简单得多的方法(随意更改悬停样式):
HTML:
<button id=Button>Button Title</button>
CSS:
.HoverClass1:hover {color: blue !important; background-color: green !important;}
.HoverClass2:hover {color: red !important; background-color: yellow !important;}
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');
答案 9 :(得分:1)
您可以创建一个CSS变量,然后在JS中对其进行更改。
:root {
--variableName: (variableValue);
}
要在JS中进行更改,我做了以下方便的小功能:
var cssVarGet = function(name) {
return getComputedStyle(document.documentElement).getPropertyValue(name);
};
和
var cssVarSet = function(name, val) {
document.documentElement.style.setProperty(name, val);
};
您可以根据需要创建任意多个CSS变量,但我在函数中未发现任何错误; 之后,您所要做的就是将其嵌入到CSS中:
table td:hover {
background: var(--variableName);
}
然后是bam,这是一个仅需要一些CSS和2个JS函数的解决方案!
答案 10 :(得分:0)
当您检测到设备支持触摸时,我建议将所有: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');
}
}
}
}
}
}
答案 11 :(得分:0)
您可以使用鼠标事件进行悬停控制。 例如,当您将鼠标悬停在该元素上时,以下代码将变为可见。
var foo = document.getElementById("foo");
foo.addEventListener('mouseover',function(){
foo.style.display="block";
})
foo.addEventListener('mouseleave',function(){
foo.style.display="none";
})
答案 12 :(得分:0)
有一些同样的问题,使用 addEventListener 来处理事件“mousenter”、“mouseleave”:
let DOMelement = document.querySelector('CSS selector for your HTML element');
// if you want to change e.g color:
let origColorStyle = DOMelement.style.color;
DOMelement.addEventListener("mouseenter", (event) => { event.target.style.color = "red" });
DOMelement.addEventListener("mouseleave", (event) => { event.target.style.color = origColorStyle })
或者当光标位于 DOM 元素上方时的其他样式。 DOMElement 可以通过多种方式选择。
答案 13 :(得分:-1)
如果您使用轻量级的html ux lang check here an example,请输入:
div root
.onmouseover = ev => {root.style.backgroundColor='red'}
.onmouseleave = ev => {root.style.backgroundColor='initial'}
上面的代码执行css:hover元标记。