有什么方法可以从 css 调用我的 JavaScript 函数吗?
对于 ex 这里是样式:
.first-nav li a:hover,
.first-nav li.hover a {
margin:-3px 0 -1px;
height:30px;
position:relative;
background:url(../images/nav-hover.jpg) no-repeat;
}
我想在 anchor 悬停时调用一个 JS 函数。
最佳答案
不,您不能直接从 CSS 触发 JavaScript。
您可以做的是使用 CSS 选择器以这种方式找到您想要观察的元素,然后观察鼠标事件。标准事件是 mouseover
和 mouseout
,但使用它们可能有点棘手,因为它们会冒泡(例如,您会得到 mouseout
,每当鼠标离开任何后代元素时)。但是,如果有适当的逻辑,它们就不会太糟糕,事实上,如果你有很多这样的东西,你可能想要使用 mouseover
和 mouseout
而不是下面的替代方案,因为您可以将它们设置在父容器上,然后计算出涉及哪个后代元素,这在某些情况下可能更简单(而在其他情况下更复杂)。
IE 提供了 mouseenter
和 mouseleave
,它们更容易使用,因为它们不会冒泡,但是(当然)特定于 IE。这些非常方便,以至于框架甚至在不支持它们的浏览器中也开始支持它们; Prototype和 jQuery例如,提供它们,如果其他一些框架也这样做,我也不会太惊讶。 jQuery 还提供了方便的 hover
功能,这将非常接近您想要的:
// jQuery
$(".first-nav li a").hover(
function(event) {
// The mouse has entered the element, can reference the element via 'this'
},
function (event) {
// The mouse has left the element, can reference the element via 'this'
}
);
...这实际上只是设置 mouseenter
和 mouseleave
处理程序的快捷方式,但仍然非常简洁。
在 Prototype 中它非常相似:
// Prototype
$$(".first-nav li a")
.invoke("observe", "mouseenter", function(event) {
// The mouse has entered the element, can reference the element via 'this'
})
.invoke("observe", "mouseleave", function(event) {
// The mouse has left the element, can reference the element via 'this'
});
(OT:在这两种情况下,我都使用了匿名内联函数表达式,只是为了避免给人留下必须使用命名函数的印象。不过,我始终建议在生产代码中使用命名函数。 )
关于javascript - 从 CSS 函数调用 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2446598/