在没有变换/翻译的情况下缩放鼠标位置上的图像

时间:2015-06-11 15:09:06

标签: javascript html css

我找到了一个关于在鼠标滚轮上缩放HTML图像的简单示例。不幸的是,在我的情况下,我无法使用CSS"转换/翻译"和" transformOrigin"因为图像的顶部/左侧位置保持不变,但必须进行更改(例如,当图像变得足够大并且到达左侧屏幕时 - '左侧位置必须为" ; 0",不是" 500px"如我的例子所示。)

我的代码:

<!doctype html>
<html lang="en">
<head>
    <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>

    <script type="text/javascript">
        window.onload = function() {
            scale = 1;  // scale of the image
            xLast = 0;  // last x location on the screen
            yLast = 0;  // last y location on the screen
            xImage = 0; // last x location on the image
            yImage = 0; // last y location on the image
            var mousewheelevt=(/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x

            if (document.attachEvent) //if IE (and Opera depending on user setting)
                document.attachEvent("on"+mousewheelevt, zoomImg)
            else if (document.addEventListener) //WC3 browsers
                document.addEventListener(mousewheelevt, zoomImg, false)
        }

        function zoomImg(e){
            var evt = window.event || e  // equalize event object
            var delta = evt.detail? evt.detail*(-120) : evt.wheelDelta  // check for detail first so Opera uses that instead of wheelDelta
            var imgg = document.getElementById('imgg');

            // find current location on screen 
            var xScreen = e.pageX - imgg.offsetLeft;
            var yScreen = e.pageY - imgg.offsetTop;

            // find current location on the image at the current scale
            xImage = xImage + ((xScreen - xLast) / scale);
            yImage = yImage + ((yScreen - yLast) / scale);

            // determine the new scale
            if (delta > 0)
            {
                if (scale < 5)
                    scale += 0.1;
            }
            else
            {
                if (scale > 1)
                    scale -= 0.1;
            }

            // determine the location on the screen at the new scale
            var xNew = (xScreen - xImage) / scale;
            var yNew = (yScreen - yImage) / scale;

            // save the current screen location
            xLast = xScreen;
            yLast = yScreen;

            imgg.style.transform = 'scale(' + scale + ')' + 'translate(' + xNew + 'px, ' + yNew + 'px' + ')';
            imgg.style.transformOrigin = xImage + 'px ' + yImage + 'px';
        }
    </script>
</head>
<body>
<img id="imgg" src="http://www.baytrail.org/vtour/map4/access/CyteHils/Bayview_Tr_Grn_Hills.JPG" style="position:absolute; top:300px; left:500px;">
</body>
</html>

在我看来,所有系数都是已知的,我只需要替换这2行来影响位置,但我找不到正确的方法:

imgg.style.transform = 'scale(' + scale + ')' + 'translate(' + xNew + 'px, ' + yNew + 'px' + ')';
imgg.style.transformOrigin = xImage + 'px ' + yImage + 'px';

我该怎么做?如果可能的话,请用CSS&#34; scale&#34;来展示一个例子。和&#34;缩放&#34;功能

0 个答案:

没有答案
相关问题