jquery悬停滚动条不能悬停

时间:2017-12-19 17:57:29

标签: jquery

我正在制作一个带有jquery的简单滚动条用于学习。但它只在悬停时运行一次。怎么解决?这是我的秘密: -

$(document).ready(function(){
  $('.scrollbar').hover(function(e){
    var y = e.pageY - $(this).offset().top;
    $(this).children('.scroll-but').css({
      'top': y + 'px'
    });
  })
});
.scrollbar{
  position:relative;
  width:10px;
  height:500px;
  background:red;
}
.scroll-but{
  position:absolute;
  width:10px;
  height:10px;
  background:blue;
  right:0;
  top:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scrollbar"><div class="scroll-but"></div></div>

1 个答案:

答案 0 :(得分:3)

由于附加的事件处理程序是.hover,该函数仅在触发悬停事件时运行,如果将鼠标移动到目标元素内,则不会触发另一个悬停事件。

要做到这一点,你必须使用.mousemove事件,它会在指针在目标元素上移动时跟踪指针,并为你提供预期的结果。

&#13;
&#13;
$(document).ready(function(){
  $('.scrollbar').mousemove(function(e){
    var y = e.pageY - $(this).offset().top;
    $(this).children('.scroll-but').css({
      'top': y + 'px'
    });
  })
});
&#13;
.scrollbar{
  position:relative;
  width:10px;
  height:500px;
  background:red;
}
.scroll-but{
  position:absolute;
  width:10px;
  height:10px;
  background:blue;
  right:0;
  top:0;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scrollbar"><div class="scroll-but"></div></div>
&#13;
&#13;
&#13;

相关问题