2

I have two images. I am trying to display one when the browser resizes left, and the other when it resizes right.

    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;

However, it seems like my function only begins to works if last_pos_x is declared outside of the function, which is clearly wrong because it will only store window.screenX from load.

Any help would be greatly appreciated

4

1 回答 1

1

最简单的解决方案是使用 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;
于 2015-02-20T05:44:23.773 回答