<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>可拖动的div</title>
<style type="text/css">
*{
margin:0;
padding: 0;
}
#div {
position: absolute;
width: 300px;
height: 300px;
border: 10px solid pink;
}
</style>
</head>
<body>
<div id="div">
<div id = "image" style="height: 300px;width: 300px">
<img style="width: 100%;height: 100% "src="image/picture.jpg" draggable='false'>
</div>
</div>
<script src="test7.js">
</script>
</body>
</html>
var div = document.getElementById("div");
var draggable = false;
var x,y;
div.onmousedown = function (e) {
e = e || window.event;
x = e.clientX - div.offsetLeft;
y = e.clientY - div.offsetTop;
draggable = true;
};
div.onmousemove = function (e) {
if (draggable==true) {
e = e || window.event;
div.style.left = e.clientX - x + "px";
div.style.top = e.clientY - y + "px";
}
};
div.onmouseup = function (e) {
draggable = false;
};
div.onmouseleave = function (e) {
draggable = false;
};
image.onmousemove = function (e) {
draggable = false;
};
参考GPT和自己的思路:
要在图片边缘5px以内调整大小,可以使用CSS属性resize来实现。将图片所在的div添加resize: both属性即可启用调整大小功能。同时,将div的border-width属性设置为15px,即可让调整大小的手柄位于边框内5px范围内。
至于拖动过快的问题,可以在mousedown事件中添加一个setTimeout定时器,限制移动的速度。在mousemove和mouseup事件中也需要清除定时器,以确保拖动流畅。
修改后的代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>可拖动的div</title>
<style type="text/css">
*{
margin:0;
padding: 0;
}
#div {
position: absolute;
width: 300px;
height: 300px;
border: 15px solid pink;
resize: both;
overflow: auto;
}
#image {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="div">
<div id="image">
<img src="image/picture.jpg" draggable='false'>
</div>
</div>
<script>
var div = document.getElementById("div");
var draggable = false;
var x, y, timeout;
div.onmousedown = function (e) {
e = e || window.event;
x = e.clientX - div.offsetLeft;
y = e.clientY - div.offsetTop;
draggable = true;
timeout = setTimeout(function() {
div.style.cursor = "move";
}, 500);
};
div.onmousemove = function (e) {
if (draggable) {
e = e || window.event;
div.style.left = e.clientX - x + "px";
div.style.top = e.clientY - y + "px";
clearTimeout(timeout);
div.style.cursor = "move";
}
};
div.onmouseup = function (e) {
draggable = false;
div.style.cursor = "default";
};
div.onmouseleave = function (e) {
if (draggable) {
draggable = false;
div.style.cursor = "default";
}
};
</script>
</body>
</html>