Div仅在特定父级内跟随光标

时间:2017-10-26 13:25:21

标签: javascript jquery css cursor mouseevent

我希望div .drag-indicator跟随光标,并在点击发生后消失。下面的代码实现了这一点,但是我只希望在将鼠标悬停在特定div .carousel上时发生此行为。当前代码使.drag-indicator跟随鼠标,无论屏幕上的位置如何,当进行任何点击时,不仅仅是在该div内。

我确信我的代码也可以稍微简化,所以这里的任何建议都会很棒。我想把它变成一个单一的功能。

感谢。



/* Follow cursor */
$(document).on('mousemove', function(e) {
  $('.drag-indicator').css({
    left: e.pageX,
    top: e.pageY
  });
});

/* Hide when clicked */
$(document).on('mousedown', function(e) {
  $('.drag-indicator').fadeOut(300)
});

.drag-indicator {
  position: absolute;
  width: 50px;
  height: 50px;
  border-radius: 100%;
  background-color: red;
  z-index: 9999;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="carousel">
  <div class="carousel-cell">CELL CONTENT</div>
  <div class="carousel-cell">CELL CONTENT</div>
  <div class="carousel-cell">CELL CONTENT</div>
  <div class="drag-indicator">DRAG INDICATOR</div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

要根据需要进行此操作,请将事件处理程序直接附加到.carousel而不是document

&#13;
&#13;
$('.carousel').on({
  mousemove: function(e) {
    $('.drag-indicator').css({
      left: e.pageX,
      top: e.pageY
    })
  },
  mousedown: function(e) {
    $('.drag-indicator').fadeOut(300)
  }
});
&#13;
.drag-indicator {
  position: absolute;
  width: 50px;
  height: 50px;
  border-radius: 100%;
  background-color: red;
  z-index: 9999;
}

.carousel {
  border: 1px solid #C00;
}

.carousel .drag-indicator {
  display: none;
}
.carousel:hover .drag-indicator {
  display: block;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="carousel">
  <div class="carousel-cell">CELL CONTENT</div>
  <div class="carousel-cell">CELL CONTENT</div>
  <div class="carousel-cell">CELL CONTENT</div>
  <div class="drag-indicator">DRAG INDICATOR</div>
</div>
&#13;
&#13;
&#13;