需求如下:
按下鼠标进行拖拽,让元素跟随鼠标进行移动,鼠标抬起,元素停止移动。
解析:
鼠标按下事件:onmousedown
鼠标移动事件:onmousemove
鼠标抬起事件:onmouseup
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#chatFrame{
width: 300px;
height: 300px;
position: absolute;
}
</style>
</head>
<body>
<div id="chatFrame" style="width: 300px;height: 300px;background-color: yellowgreen;"></div>
<script>
var div = document.getElementById("chatFrame");
var isDragging = false; // 用于标识是否正在拖拽
// 鼠标按下事件
div.onmousedown = function(event) {
isDragging = false; // 每次鼠标按下时重置拖拽标识
if (div.setCapture !== undefined) {
div.setCapture();
}
var disX = event.clientX - div.offsetLeft;
var disY = event.clientY - div.offsetTop;
// 鼠标移动事件
document.onmousemove = function(event) {
isDragging = true; // 如果发生了移动,认为发生了拖拽
var x = event.clientX - disX;
var y = event.clientY - disY;
div.style.left = x + 'px';
div.style.top = y + 'px';
};
// 鼠标抬起事件
document.onmouseup = function() {
if (div.releaseCapture !== undefined) {
div.releaseCapture();
}
document.onmousemove = null;
// 如果没有发生拖拽,则执行点击事件的默认行为
if (!isDragging) {
handleIm();
}
};
return false; // 阻止默认行为
};
// 鼠标点击事件处理函数
function handleIm() {
console.log("Handle click event");
// 在这里添加你希望执行的点击事件的逻辑
}
</script>
</body>
</html>