简体   繁体   English

悬停在元素上时使图像跟随光标

[英]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位置,并将图像的topleft样式位置设置为这些位置。

<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.

相关问题 将鼠标悬停在图像上时,如何使信息文本出现并遵循 cursor? - How to make info text appear and follow the cursor when hovering over image? 悬停在图像上时,只显示光标所在的部分 - When hovering over image, only display the part where the cursor is over it 悬停在元素上时使功能停止 - Make function stop when hovering over an element 如何使HTML元素仅在悬停时跟随光标,而不是其他方式? - How to make a HTML element follow your cursor only when hovered over, and not otherwise? 元素仅在鼠标悬停在按钮上时跟随光标 - Element Follows Cursor Only When Hovering Over Button 将鼠标悬停在链接上时在 cursor position 显示图像 - Display an image at cursor position when hovering over a link 悬停在另一个元素上时,使一个元素出现并进行调整 - Make an element appear and make adjustments when hovering over another element 悬停在WMS层上时的Leaflet.js光标 - Leafletjs Cursor when hovering over WMS Layer 将鼠标悬停在图像上时,如何显示带有xy坐标的十字光标? - How could I display a crosshair cursor with x-y coordinates when hovering over an image? 将鼠标悬停在帖子链接上时,可以将帖子缩略图用作光标图像吗? (WordPress的) - Can I use post thumbnail as cursor image when hovering over post link? (wordpress)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM