开发者

Picture follow a mouse in a <div>

开发者 https://www.devze.com 2023-03-09 01:35 出处:网络
How can I make a picture follow the mouse in a specific <div>? I know that I can get the mouse position from e.pageX & e.pageY and开发者_JAVA技巧 with the code document.onmousemove = follow

How can I make a picture follow the mouse in a specific <div>?

I know that I can get the mouse position from e.pageX & e.pageY and开发者_JAVA技巧 with the code document.onmousemove = followmouse;. Run the followmouse function every moment the mouse move in a page and in the followmouse function, set the picture position to the mouse position. For the exact question I asked here (how can I make a picture follow the mouse in a specific <div>), I have this idea:

Get my div top, left, width, and height and do some math and if mouse go out of the div, set visibility:hidden for the picture.

But isn't there any simple way to do this?


Let's assume you have some HTML like this,

<div id="mydiv" style="width: 300px; height: 300px;"></div>
<img id="myimg" style="position: absolute;" alt="" />

then

document.getElementById("mydiv").onmousemove = function(e) {
    document.getElementById("myimg").style.top = e.pageY*1 + 5 + "px";
    document.getElementById("myimg").style.left = e.pageX*1 + 5 + "px";
}

would move your picture to the mouse only if the mouse is over the div.


So long as the picture is actually contained in the div and you move it relative to its normal position, then I think setting overflow:hidden on the containing div should work. When I say "setting", I don't mean every time the mouse moves outside, but just once in the main CSS.

0

精彩评论

暂无评论...
验证码 换一张
取 消