<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
img {
width: 200px;
height: 200px;
position: absolute;
left: 0px;
top: 0px;
}
</style>
</head>
<body>
<img src="1.jpg" id='pic' draggable='false'>
<script type="text/javascript">
const newImg = document.getElementById('pic');
let flag = false; // 控制图片位移事件
let moveX, moveY;
let multiple = 1; // 放大的值
// 鼠标按下事件
newImg.onmousedown = function (e) {
flag = true;
const { clientX, clientY } = e;
// 鼠标相对于图片的位置
moveX = clientX - newImg.offsetLeft;
moveY = clientY - newImg.offsetTop;
// 鼠标移动
const HandleMove = (n) => {
if (flag) {
const { clientX, clientY } = n;
newImg.style.left = `${clientX - moveX}px`;
newImg.style.top = `${clientY - moveY}px`;
}
}
// 鼠标弹起
const HandleUp = () => {
document.removeEventListener('mousemove', HandleMove);
document.removeEventListener('mouseup', HandleMove);
flag = false;
}
document.addEventListener('mousemove', HandleMove);
document.addEventListener('mouseup', HandleUp);
};
// 滚轮事件
const handleMouseEvent = (e) => {
if (newImg) {
if (event.wheelDelta > 0) {
multiple += 0.1;
} else {
multiple -= 0.1;
}
if (multiple < 0) {
multiple = 0;
}
multiple = multiple < 0 ? 0 : multiple;
newImg.style.transform = `scale(${multiple})`;
}
}
window.onload = function () {
document.addEventListener('mousewheel', handleMouseEvent); // 添加鼠标滚轮事件
};
</script>
</body>
</html>```
js实现图片放大缩小平移
最新推荐文章于 2024-11-04 16:49:48 发布