<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#box {
width: 80px;
height: 80px;
background-color: red;
position: absolute;
left: 80px;
top: 100px;
}
</style>
<script src="jquery-3.3.1.js"></script>
</head>
<body>
<div id="box"></div>
<script>
$(function() {
$('#box').mousedown(function(e) {
var e = e || window.event;
var x= e.clientX - $(this).offset().left - $(this).outerWidth() / 2;
var y= e.clientY - $(this).offset().top - $(this).outerHeight() / 2;
$(document).mousemove(function(e) {
var e = e || window.event;
var l=e.clientX-x;
var t=e.clientY-y;
if (l < 0) {
l = 0;
} else if (l > $(this).scrollWidth - $('#box').outerWidth()) {
l = $(this).scrollWidth - $('#box').outerWidth;
}
if(t<0){
t=0;
}else if(t>$(this).scrollHeight-$('#box').outerHeight()){
t=$(this).scrollHeight-$('#box').outerHeight();
}
$('#box').css({
'position':'absolute',
'left':l,
'top':t
})
})
$(document).unbind('mouseup');
})
})
</script>
</body>
</html>
jquery实现拖拽功能
最新推荐文章于 2023-04-07 17:21:08 发布