[英]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
事件,而是在您希望標題懸停的元素上使用。 您可以使用pageX
和pageY
屬性來獲取文檔上指針的坐標,並將這些值應用於title
元素的left
和top
屬性
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.