检查 JavaScript 中的元素是否被悬停。

huangapple go评论56阅读模式
英文:

check if a element is being hovered on in javascript

问题

我有一个用JavaScript制作的画布图片,我想要检查鼠标光标是否悬停在画布上。这是我的代码样子:

window.onload = function() {     
     var Gamecanvas = document.getElementById('game');
     var GameCTX = Gamecanvas.getContext('2d');
     function soapDraw() {
         var soap = new Image();
         soap.src = 'Soap.png';         
         soap.onload = function() {
              GameCTX.drawImage(soap, 5, 5);
         };
     };
     soapDraw(); 
}

这段代码加载了一张肥皂的图片,我想要检查鼠标光标是否悬停在肥皂上,尽管我还没有进行移动部分的操作...

我不想要任何jQuery的答案,我想要纯JavaScript的答案。

我在其他论坛上尝试过jQuery的答案,但我不懂jQuery,不知道如何调整它以满足我的需求。

编辑:这是我的网站的样子:
这个网站图片

英文:

I have a canvas picture made in javascript and i want to check if the mouse cursor is hovering over the canvas. this is how my code looks like

window.onload = function() {     
     var Gamecanvas = document.getElementById('game');
     var GameCTX = Gamecanvas.getContext('2d');
     function soapDraw() {
         var soap = new Image();
         soap.src = 'Soap.png';         
         soap.onload = function() {
              GameCTX.drawImage(soap, 5, 5);
         };
     };
     soapDraw(); 
}

this code loads a image of soap and i want to if the cursor hovers over the soap, it moves, though i am not onto the moving part yet...

I do not want any jquery answers. I want javascript non-query answers

I tried jquery answers on other forums but i have no experience with jquery and i dont know how to adjust it to my needs.

Edit: this is how my site looks like:
this website picture

答案1

得分: 0

你可以直接在画布上使用事件监听器,并监听鼠标移入事件。

Gamecanvas.addEventListener('mouseover', (event) => { /* 你的代码放在这里 */ });

要获取更详细的答案,请查看这里

英文:

you can use an event listener directly on canvas and watching for mouseover event

Gamecanvas.addEventListener('mouseover', (event) => { /* your code goes here */});

for a more complete answer look here

huangapple
  • 本文由 发表于 2023年2月24日 06:20:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75550906.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定