暂时鼠标悬停
CSS“悬停”选择器将临时样式应用于元素,但它不是确定的:
div:hover {
background-color: red;
}
我可以使用 javascript 做同样的事情,但对于多个元素来说有点复杂且不可能:
var elem = document.getElementsByTagName ("div")[0];
elem.onmouseover = function () {
this.style.backgroundColor = "red";
}
elem.onmouseout = function () {
this.style.backgroundColor = "transparent";
}
有更好的方法吗?像这样的:
document.getElementsByTagName ("div")[0].ontemporarymouseover = function () { // LoL
this.style.backgroundColor = "red";
}
谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,没有办法应用自行消失的样式。
尽管 CSS 只包含一个定义,但它实际上对应了触发
onmouseover
和onmouseout
的两种状态变化。当指针进入元素时,:hover
伪类将添加到其中,从而应用 CSS 规则。当指针离开元素时,:hover
伪类将被删除,从而使 CSS 规则不再适用。No, there is no way to apply styles that go away by themselves.
Eventhough the CSS contains only one definition, it actually corresponds to the two state changes that triggers
onmouseover
andonmouseout
. When the pointer enters the element, the:hover
pseudo class is added to it making the CSS rule apply. When the pointer leaves the element, the:hover
pseudo class is removed making the CSS rule no longer apply.在 JavaScript 中,此行为只能通过监听
mouseover
和mouseout
来处理 DOM 事件,就像您在第二个示例中所做的那样。不过,建议使用 CSS 处理悬停样式,如第一个示例所示。In JavaScript this behaviour can only be handled by listening to the
mouseover
andmouseout
DOM events, as you did in your second example. However it is recommended to handle hovering styles with CSS, as in your first example.// jQuery 'Temporary mouseevents'
我希望这是满足您需求的好方法。
// jQuery 'Temporary mouseevents'
I hope this is a good approach for what you need.
我相信如果你使用 jQuery JavaScript 框架,你可以这样做:
I believe that if you use the jQuery JavaScript framework, you can do this: