js 滚轮控制图片缩放大小和拖动

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Documenttitle>
    <style>
    .dragAble {
        position: relative;
        cursor: move;
    }
    
    .img-con {
        position: relative;
        width: 713px;
        height: 455px;
        overflow: hidden;
        border: 1px solid red;
    }
    style>
head>

<body>
    <p class="img-con"><img src="http://img03.tooopen.com/uploadfile/downs/images/20110714/sy_20110714135215645030.jpg" class="dragAble" />p>
    <script type="text/javascript" charset="utf-8">
    window.onload = function() {
            var oImg = document.getElementsByTagName("img")[0];
            function fnWheel(obj, fncc) {
                obj.onmousewheel = fn;
                if (obj.addEventListener) {
                    obj.addEventListener('DOMMouseScroll', fn, false);
                }

                function fn(ev) {
                    var oEvent = ev || window.event;
                    var down = true;

                    if (oEvent.detail) {
                        down = oEvent.detail > 0
                    } else {
                        down = oEvent.wheelDelta < 0
                    }

                    if (fncc) {
                        fncc.call(this, down, oEvent);
                    }

                    if (oEvent.preventDefault) {
                        oEvent.preventDefault();
                    }

                    return false;
                }


            };
            fnWheel(oImg, function(down, oEvent) {

                var oldWidth = this.offsetWidth;
                var oldHeight = this.offsetHeight;
                var oldLeft = this.offsetLeft;
                var oldTop = this.offsetTop;

                var scaleX = (oEvent.clientX - oldLeft) / oldWidth; //比例
                var scaleY = (oEvent.clientY - oldTop) / oldHeight;

                if (down) {
                    this.style.width = this.offsetWidth * 0.9 + "px";
                    this.style.height = this.offsetHeight * 0.9 + "px";
                } else {
                    this.style.width = this.offsetWidth * 1.1 + "px";
                    this.style.height = this.offsetHeight * 1.1 + "px";
                }

                var newWidth = this.offsetWidth;
                var newHeight = this.offsetHeight;

                this.style.left = oldLeft - scaleX * (newWidth - oldWidth) + "px";
                this.style.top = oldTop - scaleY * (newHeight - oldHeight) + "px";
            });
        }
        
                    

你可能感兴趣的:(js 滚轮控制图片缩放大小和拖动)