1

我需要在“调整大小”事件以及在 ipad 上放大/缩小之后执行某个功能。首先我做了oun事件并在监听器中引发“resize”事件:

ZoomHelper = (function () {
    var zoomListeners = [];
    var viewportScale = 1;
    var polling = false;
    function pollZoomFireEvent() {
        var widthNow = window.innerWidth;
        currentViewportScale = (window.screen.width / window.innerWidth).toPrecision(3);
        if (currentViewportScale != viewportScale) {
            viewportScale = currentViewportScale;
            for (var i = 0; i < zoomListeners.length; i++) {
                zoomListeners[i]();
            }
        }
        if (polling)
            setTimeout(arguments.callee, 500);
    }
    function startPollingIfNeeded() {
        if (zoomListeners.length == 1) {
            polling = true;
            pollZoomFireEvent();
        }
    }
    function stopPollingIfNeeded() {
        if (zoomListeners.length < 1) {
            polling = false;
        }
    }
    return {
        addZoomListener: function (func) {
            zoomListeners.push(func);
            startPollingIfNeeded();
        },
        removeZoomListener: function (func) {
            index = zoomListeners.indexOf(func);
            zoomListeners.slice(index, 1);
            stopPollingIfNeeded();
        }
    }
})();

但后来我发现如果一个页面至少有一个固定位置的元素,那么“resize”事件会在放大或缩小后自动引发:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title>
<script>
    window.onresize = onResize;
    function onResize(e) {
        console.log("resize");
    }
</script>
</head>
<body>
   <div style="position:fixed; border:5px solid red; width:50px; height:50px;">
   </div>
</body>
</html>

这是正常行为吗?这些变体中哪个更好用?或者有没有更好的方法在缩放后引发“调整大小”事件?

4

0 回答 0