繁体   English   中英

悬停在父 div 内时将 div 附加到 cursor

[英]Attach a div to cursor when hovering inside a parent div

我有一个 slider 画廊(使用 flickity),其中有 X 个画廊单元格 (divs)。 在每个 div 中,有一个图像和一个视频显示在 hover 上。还有一些文本只显示在 hover 上。我想让文本在悬停在画廊 div 内部时贴在 cursor 上。

我已经能够将文本粘贴到第一个画廊单元格上的 cursor,但它不适用于 rest。为每个单元格添加新的 JS 代码不是好的代码。

参见小提琴: https://jsfiddle.net/jxnw4pe0/

这是我的 JS:

var mydiv1=document.getElementById("myDiv1");
document.addEventListener('mousemove', function (e) {
    var x = e.pageX;
    var y = e.pageY;
    mydiv1.style.top = y + 'px';
    mydiv1.style.left = x + 'px';
});

任何使这个 JS 与所有画廊单元一起工作的帮助将不胜感激。

这按照您的要求工作,您需要将事件侦听器添加到所有元素 class .gallery-cell ,并记住获取您悬停的元素的偏移量以在适当的位置显示文本(即如果你已经滚动了)。

您用 jquery 标记了问题,所以我使用了它,因为它更简单。


 // Use JQUERY mousemove event on gallery cells $(".gallery-cell").mousemove( function(e) { // Select hovertext element within gallery cell $popup = $(this).find(".hovertext").first(); // Get offset from top var eTop = $(this).offset().top; var eLeft = $(this).offset().left; var x = e.pageX; var y = e.pageY; // Set CSS $(this).find(".hovertext").css({top: y -eTop, left: x - eLeft}); });
 h1 {color:#fff}.gallery{position:relative;}.gallery-cell { width:500px; height:200px; display:block; background: red; position:relative; margin: 5px 0; }.gallery-cell-image { object-fit: cover; width: 100%; height: 100%; }.gallery-cell-video { position: absolute; object-fit: cover; top:0; left:0; width: 100%; height: 100%; }.hovertext { position: absolute; top: 0; left:0; z-index: 100; overflow:hidden; white-space: nowrap; } #something.hovertext {visibility: hidden;} #something:hover.hovertext {visibility: visible;} #something.gallery-cell-video {visibility: hidden;} #something:hover.gallery-cell-video {visibility: visible;}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="gallery"> <div class="gallery-cell" id="something"> <img class="gallery-cell-image" src="https://agoberg.tv/tmp/blue.jpg" /> <video class="gallery-cell-video" src="https://agoberg.tv/video/B_vs_W.mp4" autoplay muted loop></video> <div class="hovertext" id="myDiv1"><h1>Some Text 1</h1></div> </div> <div class="gallery-cell" id="something" id="something"> <img class="gallery-cell-image" src="https://agoberg.tv/tmp/red.jpg" /> <video class="gallery-cell-video" src="https://agoberg.tv/video/B_vs_W.mp4" autoplay muted loop></video> <div class="hovertext" id="myDiv1"><h1>Some Text 2</h1></div> </div> <div class="gallery-cell" id="something" id="something"> <img class="gallery-cell-image" src="https://agoberg.tv/tmp/grey.jpg" /> <video class="gallery-cell-video" src="https://agoberg.tv/video/B_vs_W.mp4" autoplay muted loop></video> <div class="hovertext" id="myDiv1"><h1>Some Text 3</h1></div> </div> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM