问题描述
我想创建一个jquery函数,使它在鼠标按下时跟随div"-因此,当鼠标按钮按下时,随着鼠标移动,页面上的div跟随光标.
I wanna make a jquery function that "follow the div when it is on mousedown" - So the div on my page follows the cursor, as the mouse moves, when the mouse button is down.
并且当鼠标按钮向上时,div停留在鼠标向下的最后位置.
and when the mouse button is up the div stay in the last position the mouse down was.
<script src="jquery-2.0.3.min.js"></script>
<script>
var posX, posY;
$(document).on('click', mueve);
function mueve (e) {
posX = e.pageX - 20;
posY = e.pageY - 20;
$('.item').animate({left: posX, top: posY})
}
</script>
css:
.item{
background: #bbb;
height: 40px;
width: 40px;
position: absolute;
border-radius: 50%;
left: 0;
top: 0;
}
推荐答案
繁荣,请查看以下内容:小提琴.
Boom, check this out: Fiddle.
这是javascript:
Here's the javascript:
var posX, posY, clicked = false;
function mueve (e) {
clicked = true;
posX = e.pageX - 20;
posY = e.pageY - 20;
$('.item').animate({left: posX, top: posY});
}
$(document).on('mousedown', mueve);
$(document).on('mouseup', function(e) {
clicked = false;
});
$(document).mousemove(function(e) {
if (clicked) {
$('.item').stop(true, true);
mueve(e);
}
});
我所做的是:当您单击鼠标左键时,将变量clicked
更改为true,因此,当您移动鼠标时,它将移动带有"item"类的div.另外,在更新位置之前,您必须清除每个排队的动画.
What I did was: when you click down, you change the variable clicked
to true, so when you move the mouse it will move the div with class 'item'. Also, you have to clear each queued animation before updating positions.
这篇关于在div后面加上带有mousedown,mousemove,mouseup的jquery函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!