实现鼠标拖拽图片效果
我们需要一个图片 可以是你的女朋友 可以是男朋友 ,我就拿窝的偶像 一个大佬——>甘为例吧!
哈哈哈哈哈
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>鼠标拖拽图片移动的效果</title>
</head>
<style>#box {width: 800px;height: 700px;background-color: #f4a2a2;position: absolute;}#box img {width: 800px;height: 700px;position: absolute;}#box h1 {text-align: center;margin: 0;padding: 10px 0;color: #fff;}</style>
<body><div id="box"><h1>这是窝的偶像</h1><img src="image/gan.jpg" alt=""></div><script>let box = document.querySelector("#box")let startX = 0, startY = 0;let boxLeft = 0, boxTop = 0;box.onmousedown = function(e) {e.preventDefault(); // 阻止默认行为startX = e.clientX;startY = e.clientY;boxLeft = box.offsetLeft;boxTop = box.offsetTop;document.onmousemove = function(e2) {e2.preventDefault(); // 阻止默认行为let moveX = e2.clientX - startX;let moveY = e2.clientY - startY;box.style.left = (boxLeft + moveX) + "px";box.style.top = (boxTop + moveY) + "px";}}document.onmouseup = function() {document.onmousemove = null;}// 阻止图片的默认拖拽行为box.querySelector('img').ondragstart = function(e) {e.preventDefault();}</script>
</body>
</html>
这里从左上角拖到了右下角