使用js检测onHover(jquery或css)事件

时间:2015-04-21 00:20:15

标签: javascript jquery css

是否有一个jquery / js脚本会监听onHover事件?

我正在构建一个监听库,我们希望能够帮助网站所有者检测用户何时发起onHover事件 - 这样他们就知道它正在引起访问者/用户的注意。

enter image description here

监听onHoverStart(当他们鼠标悬停在与其关联的onHover的元素上时)& onHoverEnd(当他们离开元素时)。

2 个答案:

答案 0 :(得分:0)

这是一个简单的例子,适用于 onmouseenter onmouseleave 我从http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onmouseover修改了

当用户悬停图像时会变大。当悬停停止时,图像将恢复正常大小。您还可以自定义功能以执行您想要的操作 onmouseenter onmouseleave

<!DOCTYPE html>
<html>
<body>

<img onmouseover="WhenUserHovers(this)" onmouseout="WhenUserStopsHovering(this)" border="0" src="smiley.gif" alt="Smiley" width="32" height="32">

<p>The function WhenUserHovers() is triggered when the user moves the mouse pointer over the image.</p>
<p>The function WhenUserStopsHovering() is triggered when the mouse pointer is moved out of the image.</p>

<script>
function WhenUserHovers(x) {
    x.style.height = "64px";
    x.style.width = "64px";
}

function WhenUserStopsHovering(x) {
    x.style.height = "32px";
    x.style.width = "32px";
}
</script>

</body>
</html>

您还可以使用jQuery(javascript库) mouseenter mouseleave http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_event_mouseenter_mouseleave

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("p").mouseenter(function(){
        $("p").css("background-color", "yellow");
    });
    $("p").mouseleave(function(){
        $("p").css("background-color", "lightgray");
    });
});
</script>
</head>
<body>

<p>Move the mouse pointer over this paragraph.</p>

</body>
</html>

或jQuery的鼠标悬停 mouseout http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_event_mouseover_mouseout

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("p").mouseover(function(){
        $("p").css("background-color", "yellow");
    });
    $("p").mouseout(function(){
        $("p").css("background-color", "lightgray");
    });
});
</script>
</head>
<body>

<p>Move the mouse pointer over this paragraph.</p>

</body>
</html>

鼠标指针进入所选元素时,jQuery的 mouseenter / mouseleave mouseover / mouseout 之间的区别是 mouseenter 鼠标悬停在指针进入元素或元素的任何子元素时起作用。

答案 1 :(得分:0)

使用jquery检测悬停使用此

$("selector").hover(function(){
//do something when it is hover
},function(){
//do something when you lose hover
});

您可以在此处详细了解https://api.jquery.com/hover/