0

我在这里阅读了很多问题,但找不到解决此问题的问题。我已经编写了一个 div 来跟随我的光标。我只希望它在光标位于#backgroundiv 上时出现。我已经让它工作了,但它有时会在 chrome 上随机闪烁并在 Firefox 上完全消失。更随机的是,它有时似乎工作,然后开始闪烁。我尝试了从悬停到鼠标输入/鼠标悬停的各种方法,但似乎没有任何效果。

我想要的是当光标在#backgroundiv 上方时出现#newdot,然后在div 周围跟随光标。任何帮助将非常感激。

//hide dot when leaves the page
$(document).ready(function() {
  $("#backgroundiv").hover(function() {
    $("#newdot").removeClass("hide");
  }, function() {
    $("#newdot").addClass("hide");
  });
});

//div follows the cursor
$("#backgroundiv").on('mousemove', function(e) {
  //below centres the div
  var newdotwidth = $("#newdot").width() / 2;
  $('#newdot').css({
    left: e.pageX - newdotwidth,
    top: e.pageY - newdotwidth
  });
});
//tried below too but it doesn't work
/*$(document).ready(function(){
           $("#backgroundiv").mouseenter(function(){
           $("#newdot").removeClass("hide");
           });
           $("#backgroundiv").mouseout(function(){
           $("#newdot").addClass("hide");
           });
        }); */
#backgroundiv {
  width: 400px;
  height: 400px;
  background-color: blue;
  z-index: 1;
}

#newdot {
  width: 40px;
  height: 40px;
  background-color: red;
  position: absolute;
  z-index: 2;
}

.hide {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="newdot"></div>
<div id="backgroundiv"></div>

4

1 回答 1

2

没有问题,而是一种合乎逻辑的行为,当您将鼠标悬停在您触发的蓝色 div 上时,mouseenter您会删除该类,并且当您将鼠标悬停在从蓝色 div 触发的红色 div 时,您会看到红色的,mouseleave因此您添加了该类并隐藏红色的。现在红色被隐藏了,您再次触发mouseenter蓝色 div 并再次删除该类并显示红色 div,依此类推……这是闪烁。

为避免这种情况,您可以考虑将鼠标悬停在红色框上,以在您失去蓝色悬停时使红色框出现在其悬停上。

$(document).ready(function() {
  $("#backgroundiv").hover(function() {
    $("#newdot").removeClass("hide");
  }, function() {
    $("#newdot").addClass("hide");
  });
});
//div follows the cursor
$("#backgroundiv").on('mousemove', function(e) {
  //below centres the div
  var newdotwidth = $("#newdot").width() / 2;
  $('#newdot').css({
    left: e.pageX - newdotwidth,
    top: e.pageY - newdotwidth
  });
});
#backgroundiv {
  width: 400px;
  height: 400px;
  background-color: blue;
  z-index: 1;
}

#newdot {
  width: 40px;
  height: 40px;
  background-color: red;
  position: absolute;
  z-index: 2;
}

.hide {
  display: none;
}


/* Added this code */

#newdot:hover {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="newdot">
</div>
<div id="backgroundiv">
</div>

于 2018-05-12T12:05:10.807 回答