多个元素拖拽
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>多个元素拖拽</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.mark {
position: absolute;
width: 150px;
height: 150px;
text-align: center;
line-height: 150px;
color: #fff;
font-family: "微软雅黑";
font-size: 18px;
border-radius: 50%;
cursor: pointer;
}
</style>
</head>
<body>
<div style="top: 0; left: 0;background: green;" class="mark">绿叶</div>
<div style="top: 200px; left: 300px; background: lightcoral;" class=" mark">红花</div>
<div style="top: 500px; left: 200px; background: darkorange;" class=" mark">黄花</div>
</body>
</html>
<script src="js/jquery-1.11.0.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
var $mark = $('.mark')
$mark.each(function(item,indexx){
$(this).bind('mousedown', downFn)
})
function downFn(e) {
//当鼠标按下的时候,记录当前的鼠标信息值和盒子当前位置(可以用全局变量也可以用增加自定义属性)
$(this).attr({
markLeft: parseFloat($(this).css('left')),
markTop: parseFloat($(this).css('top')),
markX: e.clientX,
markY: e.clientY
})
this.Move = moveFn.bind(this)//给当前元素增加一个Move方法,在用bind改变this关键字
this.UP = upFn.bind(this)
if(this.setCapture) { //将鼠标和这个盒子绑定在一起,要不然鼠标移动过快盒子跟不上啊注意:ie火狐都兼容,反倒是谷歌不兼容
this.setCapture()
$(this).bind('mousemove', moveFn).bind('mouseup', upFn)//给当前元素绑定鼠标移动和离开方法
} else {
//如果是火狐浏览器
$(document).bind('mousemove', this.Move).bind('mouseup', this.UP)//给整个文档绑定方法
}
e.preventDefault();//阻止默认行为
}
function moveFn(e) {
//用房钱鼠标信息的xy值减去开始时候的xy值,就是移动的距离,那再在mark的left和top的基础上加上这个距离,就是移动后的位置了
//获取当前xy值
var changeX = e.clientX - $(this).attr('markX');//现在坐标减去原始坐标等于移动的距离
var changeY = e.clientY - $(this).attr('markY');
var curL = parseFloat($(this).attr('markLeft')) + changeX;//原始的left加上移动的距离等于现在的left
var curY = parseFloat($(this).attr('markTop')) + changeY
$(this).css({
'left': curL,
'top': curY
})
}
function upFn(e) {
if(this.releaseCapture) {
this.releaseCapture() //将鼠标和盒子解绑
$(this).unbind('mousemove', moveFn).unbind('mouseup', upFn)
} else {
$(document).unbind('mousemove', this.moveFn)
$(document).unbind('mousemove', this.Move).unbind('mouseup', this.UP)
}
}
</script>
这个等以后实际应用的时候还要设置边界,防止元素拖拽出来,以后在加动画^_^
这里要注意的就是bind的用法
call,apply,bind的相同 :
他们都是改变上下文,就是this关键字的指向,可以后续传参;
区别:
call和apply都是改变this关键字之后立即执行,他俩的 区别就是call是依次传参,apply是直接将这些参数放到一个数组中再传递,而bind是只改变this关键字,但是不执行