根据调整大小的方向显示不同的图像

Displaying different image based on direction of resize

本文关键字:显示 图像 方向 调整      更新时间:2024-01-28

我有两个图像。当浏览器向左调整大小时,我尝试显示一个,当浏览器向右调整大小时显示另一个。

    function adjustDirection() {
        var last_pos_x = window.screenX;
        if ( last_pos_x < window.screenX) {
            document.getElementById("logo").style.backgroundImage = "url('logoRight.png')";
        } else if (last_pos_x > window.screenX) {
            document.getElementById("logo").style.backgroundImage = "url('logoLeft.png')";
        }
    }
    window.onresize = adjustDirection;

然而,我的函数似乎只有在函数外声明last_pos_x时才开始工作,这显然是错误的,因为它只会从加载中存储window.screenX

如有任何帮助,将不胜感激

最简单的解决方案是使用jQuery。将posX值存储在DOM中并检索

HTML

<div id="aaa" data-posx="0"></div>

Javascript

function adjustDirection() {
        var last_pos_x = $("#id").attr("data-posx");
        $("#id").attr("data-posx",window.screenX);
        if ( last_pos_x < window.screenX) {
            document.getElementById("logo").style.backgroundImage = "url('logoRight.png')";
        } else if (last_pos_x > window.screenX) {
            document.getElementById("logo").style.backgroundImage = "url('logoLeft.png')";
        }
    }
    window.onresize = adjustDirection;

只需js:的新代码

function adjustDirection() {
    var last_pos_x = window.screenX;
    return function() {
        if (last_pos_x < window.screenX) {
            document.getElementById("logo").style.backgroundImage = "url('logoRight.png')";
        } else if (last_pos_x > window.screenX) {
            document.getElementById("logo").style.backgroundImage = "url('logoLeft.png')";
        }
        last_pos_x = window.screenX;
    }
};
var z = adjustDirection();
window.onresize = z;