js实现鼠标图片放大缩小
js实现鼠标图片放大缩小
<!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>
</head>
<body>
<img id="img" src="http://blog.aoxuelingshuang.com/ico/log.png?v=1.0.0.5" alt="" style="width: 100px;">
<script>
const img = document.querySelector('#img');
RotateWheel(img);
function RotateWheel(el) {
document.onwheel = (e) => {
let delta = (e.wheelDelta && (e.wheelDelta > 0 ? 1 : -1));
if (delta > 0) {//放大
// 向上滚
let oWidth = el.offsetWidth;//取得图片的实际宽度
let oHeight = el.offsetHeight; //取得图片的实际高度
el.style.width = (oWidth + 50) + "px"
el.style.height = (oHeight + 50 / oWidth * oHeight) + "px"
} else if (delta < 0) {//缩小
//向下滚
let oWidth = el.offsetWidth; //取得图片的实际宽度
let oHeight = el.offsetHeight; //取得图片的实际高度
if (el.offsetWidth > 100 || el.offsetHeight > 75) {//判断如果图片缩小到原图大小就停止缩小(100和75分别为原图的宽高)
el.style.width = oWidth - 50 + "px"
el.style.height = oHeight - 50 / oWidth * oHeight + "px"
}
}
}
}
</script>
</body>
</html>
当页面有滚动条时,放大缩小图片页面会抖动可以禁用滚动条
const body = document.querySelector('body');
body.style.overflow = 'hidden';
本文来自博客园,作者:默永,转载请注明原文链接:https://www.cnblogs.com/Lmyong/p/16888856.html