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

标签 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>

最佳答案

要按照您的要求进行这项工作,请将事件处理程序直接附加到 .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>

关于javascript - Div 仅在特定父级内跟随光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46955601/

相关文章:

jquery - 循环关键帧css3动画8次

javascript - 如何创建一个滑动侧导航栏,在打开时使网站的其余部分变暗?

javascript - TypeScript:创建一个空类型的容器数组

javascript - 调用事件时每隔几秒运行一次代码

javascript - 使用 jquery 获取 ul 中每个 li 的 Id 或 Name

html - 需要有关 3x3 井字游戏设计的帮助。我无法摆脱 CSS 中的一些空间

javascript - 文件下载 - 如何控制文件名并尊重用户偏好?

javascript - 使用 WKWebView iOS 加载本地 HTML/Javascript

Jquery从数据函数中获取父元素

css - 如何在不给它(或其父级)明确高度的情况下防止内联 SVG 以任意高度显示?