更改: 使用 JavaScript 悬停 CSS 属性

JavaScript 如何更改 CSS :hover属性?

例如:

超文本标示语言

<table>
<tr>
<td>Hover 1</td>
<td>Hover 2</td>
</tr>
</table>

CSS

table td:hover {
background:#ff0000;
}

如何使用 JavaScript 将 td :hover属性修改为(比如说) background:#00ff00?我知道我可以使用 JavaScript 访问样式背景属性:

document.getElementsByTagName("td").style.background="#00ff00";

但是我不知道 .style JavaScript 是否与 :hover等价。

303958 次浏览

您可以通过 Javascript 更改或改变实际的 :hover选择器。但是,您可以使用 mouseenter来改变样式,并在 mouseleave上恢复(谢谢@Bryan)。

: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);

您可以更改对象的类并定义两个具有不同悬停属性的类。例如:

.stategood_enabled:hover  { background-color:green}
.stategood_enabled        { background-color:black}
.stategood_disabled:hover { background-color:red}
.stategood_disabled       { background-color:black}

我在上面发现了这个: 用 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");

如果它符合您的目的,您可以添加悬停功能,而不使用 css 和使用在 javascript 中的 onmouseover事件

下面是一个代码片段

<div id="mydiv">foo</div>


<script>
document.getElementById("mydiv").onmouseover = function()
{
this.style.backgroundColor = "blue";
}
</script>

这实际上并不是将 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”。

我曾经有过这样的需要,并创建了一个小型的库,用于维护 CSS 文档

Https://github.com/terotests/css

你可以这么说

css().bind("TD:hover", {
"background" : "00ff00"
});

它使用了上面提到的技术,并试图解决跨浏览器的问题。如果出于某种原因存在一个像 IE9这样的老浏览器,它将限制 STYLE 标记的数量,因为老的 IE 浏览器对页面上可用的 STYLE 标记的数量有这种奇怪的限制。

此外,它通过仅定期更新标记来限制标记的通信量。对创建动画类的支持也是有限的。

当您检测到设备支持触摸时,我建议将所有 :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');
}
}
}
}
}
}

声明一个全局变量:

var td

然后选择你的豚鼠 <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;

很抱歉发现这个页面晚了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');

这个问题很老了,所以我觉得我应该加一个更现代的答案。现在 CSS 变量得到了广泛的支持,可以使用它们来实现这一点,而不需要 JS 事件或 !important

以《观察家报告》为例:

<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');
});

下面是一个工作示例 https://codepen.io/ybentz/pen/RwPoeqb

您可以创建一个 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);
}

然后,砰,一个解决方案,只需要一些 CSS 和2个 JS 函数!

如果使用轻量级 html ux lang,在这里检查一个例子,请写:

div root
.onmouseover = ev => {root.style.backgroundColor='red'}
.onmouseleave = ev => {root.style.backgroundColor='initial'}

上面的代码执行 css: hover metatag。

您可以使用鼠标事件来控制类似鼠标悬停的操作。 例如,当您将该元素悬停时,下面的代码将显示出来。

var foo = document.getElementById("foo");
foo.addEventListener('mouseover',function(){
foo.style.display="block";
})
foo.addEventListener('mouseleave',function(){
foo.style.display="none";
})

遇到了一些相同的问题,使用 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 可以通过多种方式选择。

这招对我很管用

        const useStyles = makeStyles({
mystyle:{
color: "red",
FontFace: "oblique"
},
yourStyle:{
backgroundColor:"green",
border:0,
color: 'white',
"&:hover":{
backgroundColor:"skyblue",
border:0,
}
},
        

})

我正在研究悬停,能够实现他们在按钮标签,使悬停效果

<button type="submit"
style=" background-color:cornflowerblue; padding:7px; border-radius:6px"
onmouseover="this.style.cssText ='background-color:#a8ff78; padding:7px; border-radius:6px;'"
onmouseout="this.style.cssText='background-color:cornflowerblue; padding:7px; border-radius:6px'"
@click="form1()">
Login
</button>

你可以在 css 中创建一个类

.hover:hover {
background: #ff0000;
}

然后动态添加

const columns = document.querySelectorAll('table td');


for (let i = 0; i < columns.length; i++) {
columns[i].classList.add('hover');
}

但是您的 css 和 js 文件应该在 index.html 中连接

对于我自己,我发现了以下选项: 从 https://stackoverflow.com/a/70557483/18862444

const el = document.getElementById('elementId');
el.style.setProperty('--focusHeight', newFocusHeight);
el.style.setProperty('--focusWidth', newFocusWidth);
.my-class {
--focusHeight: 32px;
--focusWidth: 256px;
}


.my-class:focus {
height: var(--focusHeight);
width: var(--focusWidth);
}