本文介绍如何使用JavaScript实现页面中砖块元素的鼠标拖拽效果。通过监听mousedown、mousemove和mouseup事件,结合元素定位属性,实现点击拖动时的位置跟随。代码包含HTML结构、CSS样式及核心JS逻辑,适合前端初学者参考学习。
JavaScript实现页面元素拖拽功能详解
使用JavaScript实现一个位于页面上的砖块元素,当鼠标点击并拖动时,该砖块能够跟随鼠标在页面上移动,形成拖拽交互效果。
初始状态如下:

鼠标点击并拖动后的状态如下:

具体实现代码如下:
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
*{
margin:0px;
padding:0px;
}
#zhuantou{
width:120px;
height:60px;
background-image:url(1.jpg);
position:fixed;
left:100px;
top:50px;
}
</style>
<body>
<div id="zhuantou">
</div>
<script>
var zt=document.querySelector("#zhuantou");
var isPressed=false;
var offsetX=0;
var offsetY=0;
zt.onmousedown=function(event){
isPressed=true;
this.style.cursor="move";
offsetX=event.offsetX;
offsetY=event.offsetY;
};
zt.onmouseup=function(){
isPressed=false;
this.style.cursor="default";
};
zt.onmousemove=function(event){
if(!isPressed){
return;
}
zt.style.left=(event.clientX-offsetX)+"px";
zt.style.top=(event.clientY-offsetX)+"px";
};
</script>
</body>
</html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。