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

Div follow cursor only within specific parent

我想要一个 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>

要使这项工作按您的要求进行,请将事件处理程序直接附加到 .carousel 而不是 document:

$('.carousel').on({
  mousemove: function(e) {
    $('.drag-indicator').css({
      left: e.pageX,
      top: e.pageY
    })
  },
  mousedown: function(e) {
    $('.drag-indicator').fadeOut(300)
  }
});
.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;
}
<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>