我想在滑鼠懸停 html 元素時向滑鼠添加一個圖示,以便我可以提示用戶,他們可以右鍵單擊。
我不想替換默認游標,因為它們在平臺上有所不同,并且不需要替換默認滑鼠圖示本身。
uj5u.com熱心網友回復:
您可以mousemove在要顯示自定義游標的元素上添加一個事件偵聽器,以獲取滑鼠與元素的相對 x 和 y 坐標并將它們應用于游標的top和left樣式屬性:
element.addEventListener('mousemove', function(e){
const rect = element.getBoundingClientRect();
const [x, y] = [e.pageX - rect.left, e.pageY - Math.abs(rect.top) window.scrollY]
cursor.style.display = "block";
cursor.style.left = x "px";
cursor.style.top = y "px";
})
element.addEventListener('mouseleave', function(e){
cursor.style.display = "none"; //hide the custom cursor when they leave the element
})
#element{
height:1200px;
width:600px;
background-color:black;
position:relative;
}
#cursor{
position:absolute;
display:none;
color:white;
}
<div id="element"><div id="cursor">right click!</div></div>
請記住,此解決方案需要相對定位容器元素,因為游標是絕對定位的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/355501.html
標籤:javascript html css
下一篇:傳遞顏色作為道具
