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