js实现图片拖拽效果

//图片需要自己导入
<!doctype html>
<html>
 <head>
	<meta charset="UTF-8">
	<title>在当前显示区范围内实现点不到的小方块</title>
	<style>
		div{position:fixed;width:100px;height:100px;
			background-image:url(images/xiaoxin.gif);
      background-size:100%;
		}
	</style>
	
 </head>
 <body>
	<div id="pop"></div>
	<script>
		let pop = document.getElementById("pop")
		//定义开关变量,用于控制图片是否跟随鼠标移动
		let canMove = false;
		//在开始拖拽时,就保存鼠标距div左上角的相对位置
		let offsetX,offsetY;
		//当在pop上按下鼠标时
		pop.onmousedown=function(e){
			//可以开始拖动
			canMove=true;
			offsetX=e.offsetX;
			offsetY=e.offsetY;
		}
		//当鼠标在窗口移动时
		window.onmousemove=function(e){
				//只有当pop可以移动时
			if(canMove==true){
				//让pop跟随鼠标移动
				//开始拖拽时,立刻获得鼠标距图片左上角的相对位置
				//求pop的top和left
				let left=e.clientX-offsetX;
				let top=e.clientY-offsetY;
				//设置pop的top和left属性
					pop.style.left=left+"px";
					pop.style.top=top+"px";
			}
		}
		//当在pop上抬起鼠标按键时
		pop.onmouseup=function(){
			//停止拖拽
			canMove=false
		}	
	</script>
 </body>
</html>

在这里插入图片描述

发布了17 篇原创文章 · 获赞 0 · 访问量 245

猜你喜欢

转载自blog.csdn.net/qq_44801336/article/details/104492730