簡體   English   中英

僅在懸停框時如何使 div 跟隨鼠標指針?

[英]How to make a div follow the mouse's pointer only when hovering a box?

我是一個完全的初學者,所以有人可以幫我解決這個問題。 當您在其中一個框上進行 hover 時,我希望div class="title"跟隨該框內的 cursor 。 請香草js解決方案。 看這里的圖像 這是到目前為止的代碼:

const thumbs = document.querySelectorAll(".container .thumb");
const title = document.querySelector(".thumb .title")

function divMoves() {
    title.addEventListener("mousemove", function(e) {
        let x = e.offsetX + "px";
        let y = e.offsetY + "px";
        title.style.top = x;
        title.style.left = y;
    })
};

thumbs.forEach(thumb => {
    thumb.addEventListener("mouseover", divMoves);
    thumb.addEventListener("mouseleave");
});

您不需要在標題上使用mousemove事件,而是在您希望標題懸停的元素上使用。 您可以使用pageXpageY屬性來獲取文檔上指針的坐標,並將這些值應用於title元素的lefttop屬性

const thumbs = document.querySelectorAll(".box");
const title = document.querySelectorAll(".title")
const onMouseMove = (e, i) => {

  title[i].style.left = e.pageX + 'px';
  title[i].style.top = e.pageY + 'px';
}

thumbs.forEach((thumb, i) => {
    thumb.addEventListener("mousemove", (e) => onMouseMove(e, i));
});

在此處查看示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM