<!DOCTYPE>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>鼠标拖拽</title>
<script type="text/javascript" src="./js/jquery-1.7.2.min.js"></script>
<style type="text/css">
*{margin:0;padding:0;overflow: auto;}
html,body{width:100%;height: 100%;}
#content{width:90%;height: 90%;margin: 5%;background: red;position: relative;}
#test{width:100px;height: 100px;position: absolute;top:0;left: 5%;background: #90F58E;}
</style>
<script type="text/javascript">
$(function(){
$("#test").mousedown(function(){
var x = event.clientX - $(this).offset().left;
var y = event.clientY - $(this).offset().top;
$(this).data('x',x);
$(this).data('y',y);
$(this).data('down',true);
console.log(event);
return false;
}).mousemove(function(){
if($(this).data('down')) {
var mx = event.clientX - $(this).data('x');
var my = event.clientY - $(this).data('y');
if(mx < $("#content").offset().left) {
mx = $("#content").offset().left;
$(this).data('down',false);
} else if(mx > ($("#content").offset().left+$("#content").outerWidth()-$(this).outerWidth())) {
mx = $("#content").offset().left+$("#content").outerWidth()-$(this).outerWidth();
$(this).data('down',false);
}
if(my < $("#content").offset().top) {
my = $("#content").offset().top;
$(this).data('down',false);
} else if (my >($("#content").offset().top+$("#content").outerHeight()-$(this).outerHeight())) {
my = $("#content").offset().top+$("#content").outerHeight()-$(this).outerHeight();
$(this).data('down',false);
}
$(this).offset({left:mx,top:my});
} else {
return false;
}
}).mouseup(function(){
$(this).data('down',false);
}).mouseleave(function(){
$(this).data('down',false);
});
})
</script>
</head>
<body>
<div id="content">
<div id="test"></div>
</div>
</body>
</html>
鼠标拖拽事件
最新推荐文章于 2023-11-24 16:04:33 发布