[英]Div follow cursor only within specific parent
我希望div .drag-indicator
跟隨光標,並在單擊時消失。 下面的代碼實現了此目的,但是我只希望將.carousel
懸停在特定的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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.