jQuery 你如何用jquery让图片跟随你的鼠标指针?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1677848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you make a picture follow your mouse pointer with jquery?
提问by Majid Fouladpour
I find drag-and-drop difficult (you know, keeping the mouse button depressed while moving), and want to offer a 'select and drop' where a user clicks on an icon and clicks again on the drawing-plate to drop the corresponding element (a picture).
我发现拖放很困难(你知道,在移动时按住鼠标按钮),并希望提供一个“选择和放下”,用户点击一个图标并再次点击绘图板以放下相应的元素(图片)。
How do you do that with jquery?
你如何用 jquery 做到这一点?
Thanks.
谢谢。
Edit: I have two divs, an icons plate to select elements from, and a drawing plate where pictures are dropped. When the mouse enters the drawing plate I want a 50% opacity of the bigger image follow the mouse pointer so that the user knows by clicking where it is going to be dropped and if it overlaps with anything already on the drawing board.
编辑:我有两个 div,一个用于从中选择元素的图标板,以及一个放置图片的绘图板。当鼠标进入绘图板时,我想要更大图像的 50% 不透明度跟随鼠标指针,以便用户通过单击它将被放置的位置以及它是否与绘图板上已有的任何内容重叠。
回答by Majid Fouladpour
The answer (using James Black's help) is:
答案(使用 James Black 的帮助)是:
HTML
HTML
<div id="sketch"></div>
<img src="cat.jpg" class="follow" style="position: absolute;"/>
JQuery
查询
$("#sketch").mousemove(function(e){
$('.follow').css({'top': e.clientY - 20, 'left': e.clientX - 20});
});
Jsbin demo here.
Jsbin 演示在这里。
回答by James Black
Just store the element in some variable that is accessible to the click event.
只需将元素存储在单击事件可访问的某个变量中。
So, have an onclick on every image: $('img').bind('click', function(e) { ... });
Then, when they click, just store the targetEvent somewhere and bind a click event to the drawing-plate.
因此,对每个图像进行 onclick:$('img').bind('click', function(e) { ... });
然后,当他们单击时,只需将 targetEvent 存储在某处并将单击事件绑定到绘图板。
An interesting way would be to use a closure and bind that particular targetEvent so that in the event of a click on the drawing-plate you will know which one to move, but as long as you know, then you will just use an animation to move the img over to the new location.
一个有趣的方法是使用闭包并绑定特定的 targetEvent 以便在单击绘图板时您将知道要移动哪个,但是只要您知道,那么您只需使用动画即可将 img 移动到新位置。
I forgot, you will also need to ensure that when an image is clicked on that the event handler that is already on the drawing-plate is removed before binding a new one.
我忘了,您还需要确保在单击图像时,在绑定新图像之前删除绘图板上已经存在的事件处理程序。