【问题标题】:Div follow cursor only within specific parentdiv 仅在特定父级中跟随光标
【发布时间】:2017-10-26 13:25:21
【问题描述】:

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

【问题讨论】:

    标签: javascript jquery css cursor mouseevent


    【解决方案1】:

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

    【讨论】:

    • 太好了,谢谢罗里!效果很好,但是当不将鼠标悬停在 .carousel 上时,是否可以隐藏 .drag-indicator?目前,当悬停结束时,'drag-indicator 仅保持在最后一个已知位置。谢谢
    • 是的,你可以使用 CSS 来做到这一点。我为你更新了答案
    • 谢谢罗里,我遇到了 .fadeOut 函数的问题,它不再对我有用,但可以在您的示例中看到工作正常。有任何想法吗?另外,我在移动鼠标时会出现很多闪烁?
    • 如果看不到发生了什么,就很难诊断出任何问题,抱歉。
    • 现在已经解决了轻弹问题,这是当鼠标悬停在 .drag-indicator 上时出现的 CSS 错误。这是开发站点的隧道链接,我无法弄清楚为什么 mousedown 事件不再起作用? bc621100.ngrok.io
    猜你喜欢
    • 2021-11-30
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 2020-09-04
    • 1970-01-01
    相关资源
    最近更新 更多