js实现鼠标滚轮图片放大缩小

<!doctype html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Document</title>

</head>

<body>
    <img id="img" src="11.png" alt="" style="width:100px;">
</body>

<script>
    class Rotate {
    
    
        constructor() {
    
    
            this.el = null;
        }

        init(cls) {
    
    
            this.el = document.getElementById(cls)
            return this
        }

        RotateWheel() {
    
    

            document.onwheel = (e) => {
    
    
                let delta = (e.wheelDelta && (e.wheelDelta > 0 ? 1 : -1))

                if (delta > 0) {
    
    //放大
                    // 向上滚
                    let oWidth = this.el.offsetWidth;//取得图片的实际宽度
                    let oHeight = this.el.offsetHeight; //取得图片的实际高度

                    this.el.style.width = (oWidth + 50) + "px"
                    this.el.style.height = (oHeight + 50 / oWidth * oHeight) + "px"

                } else if (delta < 0) {
    
    //缩小
                    //向下滚
                    let oWidth = this.el.offsetWidth; //取得图片的实际宽度
                    let oHeight = this.el.offsetHeight; //取得图片的实际高度
                    if (this.el.offsetWidth > 100 || this.el.offsetHeight > 75) {
    
    //判断如果图片缩小到原图大小就停止缩小(100和75分别为原图的宽高)

                        this.el.style.width = oWidth - 50 + "px"
                        this.el.style.height = oHeight - 50 / oWidth * oHeight + "px"
                    }
                }
            }
        }


    }

    new Rotate().init("img").RotateWheel()

</script>

</html>

猜你喜欢

转载自blog.csdn.net/qq_45785424/article/details/108624325