jquery拉拽div

来源:互联网 发布:js控制标签隐藏 编辑:程序博客网 时间:2024/04/28 11:30

代码提醒:需要导入jquery库


<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script src="jquery.js"></script>
</head>
<style type="text/css">
       *{
padding: 0;
margin: 0;
}
div{
width: 110px;
height: 120px;
background: pink;
cursor: pointer;
position: absolute;
left: 0;
top: 0;
}
</style>
<script type="text/javascript">
    $(function(){
    //mousedown是相对整个document的而不是相对某个元素的
$('div').mousedown(function(e){
// e.pageX鼠标在document中点下的x轴的位置
//obj.offsetLeft 指 obj (某个选中的元素的左到document左边的位置
var positionDiv = $(this).offset();
var distenceX = e.pageX - positionDiv.left;
var distenceY = e.pageY - positionDiv.top;
//distenceX是鼠标点下的位置到div左边上的位置的距离值
$(document).mousemove(function(e){
//e.pageX这个不是上面那个e.pageX而是鼠标移动的距离;
var x = e.pageX - distenceX;
var y = e.pageY - distenceY;
//if里面的代码是防止出现滚动条
if(x<0){
x=0;
}else if(x>$(document).width()-$('div').outerWidth(true)){
//$('div').outerWidth(true)求出整个div的宽度
//x>$(document).width()-$('div').outerWidth(true)
//这个条件是判断div是否有碰到document的最右边
x = $(document).width()-$('div').outerWidth(true);
}

if(y<0){
y=0;
}else if(y>$(document).height()-$('div').outerHeight(true)){
y = $(document).height()-$('div').outerHeight(true);
}
$('div').css({
'left':x+'px',
'top':y+'px'
});
});
$(document).mouseup(function(){
$(document).off('mousemove');
});
});
});
</script>
<body>
<div></div>
</body>
</html>

0 0
原创粉丝点击