[英]Make image follow cursor when hovering over an element
I was wondering whether it is possible with JavaScript to create a <a>
element which at hover would display an image that follows the position of the mouse. 我想知道JavaScript是否可以创建<a>
元素,将其悬停时将显示跟随鼠标位置的图像。
I found a lot of solutions for the hover part, but I haven't found any which would also follow the mouse. 我为悬停部分找到了很多解决方案,但还没有找到任何可以跟随鼠标的解决方案。
In other words, on hover, the image doesn't follow the mouse but just appears and dissapears on hover, how can I modify my code in order to make it follow the mouse? 换句话说,在悬停时,图像不会跟随鼠标,而是在悬停时出现并消失,如何修改代码以使其跟随鼠标? This is what I have tried so far : 到目前为止,这是我尝试过的:
<a href="link.html" onmouseover="document.getElementById('hoverimage').style.display = 'block';" onmouseout="document.getElementById('hoverimage').style.display = 'none';">hoverlink</a> <div style="display: none;" id="hoverimage"> <img src="image.png" /> </div>
Use the clientX and clientY positions of the mouse, and set the top
and left
style positions of the image to those. 使用鼠标的clientX和clientY位置,并将图像的top
和left
样式位置设置为这些位置。
<a href="#" onmouseover="interval()">Link</a>
function interval() {
while (true) {
setInterval(showImage, 1);
}
}
function showImage() {
var x = clientX;
var y = clientY;
var image = document.getElementById("hoverimage");
image.style.left = x;
image.style.top = y;
}
Once you hover on the link, the image will move to the mouse's position once a millisecond, forever. 将鼠标悬停在链接上后,图像将永远毫秒一次移动到鼠标的位置。
It is possible. 有可能的。 You need to get mouse's clientX and clientY position when hovering over certain element (body, div, etc.) and add that coordinates to your created image 将鼠标悬停在某些元素(body,div等)上时,需要获取鼠标的clientX和clientY位置,并将该坐标添加到创建的图像中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.