[英]How to change the mouse pointer to the image that was clicked on in Javascript
我正在做一個植物生長模擬器來教孩子們關於植物的知識。 有一些有關更改指針的線程,例如: JavaScript如何將鼠標光標更改為圖像? 在C#中單擊圖像時如何將鼠標指針更改為圖像
但是,關注點有所不同。 我要做的是將鼠標指針本身更改為被單擊的圖像,這樣它會給出類似以下內容:
我不知道我是否應該嘗試在click事件上更改指針或使該指針不可見並向其添加所選圖像的副本,因此我希望對此有所幫助。
在JS中,只需執行以下操作:
document.body.style.cursor = "url([url]), pointer"
例如:
document.body.style.cursor = "url(http://bringerp.free.fr/Files/RotMG/cursor.gif), pointer"
要替換為默認光標,請將光標樣式更改為空:
document.body.style.cursor = ""
要按需更改鼠標光標,您必須將點擊偵聽器添加到相關元素。 例如:
const src = 'https://www.gravatar.com/avatar/2f2eaccac43433e0bdd0b9f795286423?s=32&d=identicon&r=PG&f=1'; const docStyle = document.body.style; document.querySelector('img').addEventListener('click', () => { if (!docStyle.cursor) docStyle.cursor = `url('${src}'), default`; else docStyle.cursor = null; });
div { height: 300px; background-color: green; }
<div> <img src="https://www.gravatar.com/avatar/2f2eaccac43433e0bdd0b9f795286423?s=32&d=identicon&r=PG&f=1"> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.