悬停时同时触发mouseenter和mouseout

时间:2018-10-18 13:18:39

标签: jquery

我的jQuery如下所示:

$('h1').mouseenter(function(event) {
    console.log("in");
    $('.cursor:nth-child(2)').animate({height: "60px", width: "60px"}, 300)
});
$('h1').mouseleave(function(event) {
    console.log("out");
    $('.cursor:nth-child(2)').animate({height: "30px", width: "30px"}, 300)
});

相关的CSS在这里:

.cursor:nth-child(2) {
  border: 1px solid white;
  height: 30px;
  width: 30px;
}

相关的HTML是H1标签。我希望发生的事情很简单-.cursor div在光标悬停在H1元素上时扩展,而在没有时缩小到大小。

但是,当我将鼠标悬停在元素上时,控制台会连续登录(登录)和(登录)数百次。 .hover()也发生同样的事情。

以下是指向Codepen的链接:https://codepen.io/DrSuave/pen/BqrxER

任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:1)

两个问题

1。数百个控制台日志

mousemove事件仅通过少量持续的鼠标移动就可以触发数百次

  

在移动指针设备时事件的发生频率是特定于实现,设备和平台的,但是应该触发多个连续的mousemove事件以实现指针设备的持续移动,而不是针对每个实例的单个事件鼠标移动。

每次触发时,您都在添加另一个 mouseenter另一个 mouseleave事件。您的inout记录数百次的原因是,您已重复地将相同事件重复数百次。

简单的解决方案是将mouseentermouseleave事件处理程序移到$(document).mousemove(function() { ... })的之外。


2。光标阻止了点击/悬停事件

您的cursor阻止了您的鼠标事件,因此您需要向其中添加pointer-events: none。这将允许鼠标事件(例如hoverclick等)通过穿过,就好像它不在那里一样。

答案 1 :(得分:1)

确保标题始终保持在最前面。并在标题元素上添加透明背景。

CSS

...
h1 {
    position: relative;
    z-index: 999999;
    background: transparent;
}

正在工作的小提琴:https://codepen.io/todorutandrei/pen/YJaOzg?editors=1111

相关问题