将一个div拖拽到当前页面任意位置,鼠标松开之后div固定在松开时的位置。
上面是效果。
下面是源码:
<!DOCTYPE html>
<html>
<head>
<meta charset="{CHARSET}">
<title></title>
<style type="text/css">
.popBox{
position: relative;
background: red;
width: 500px;
height: 500px;
}
</style>
</head>
<body>
<div class="popBox" >
</div>
<script type="text/javascript" src="jquery-1.8.2.min.js"> </script>
<script type="text/javascript">
function drag(){
var obj=$('.popBox');
obj.bind('mousedown',start);
function start(e){
var ol=obj.position().left;
var ot=obj.position().top;
deltaX=e.pageX-ol;
deltaY=e.pageY-ot;
$(document).bind({
'mousemove':move,
'mouseup':stop
});
return false;
}
function move(e){
obj.css({
"left":(e.pageX-deltaX),
"top":(e.pageY-deltaY)
});
return false;
}
function stop(){
$(document).unbind({
'mousemove':move,
'mouseup':stop
})
}
}
drag();
</script>
</body>
</html>
主要注意点有两点:
1.引入jquery-1.8.2.min.js(仍以版本都可以)。
2.position: relative;(relative生成相对定位的元素,相对于其正常位置进行定位。relative在轮播时经常被用到)。