【问题标题】:Displaying different image based on direction of resize根据调整大小的方向显示不同的图像
【发布时间】:2015-02-20 05:23:08
【问题描述】:

我有两张图片。我试图在浏览器向左调整大小时显示一个,而在向右调整大小时显示另一个。

    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

任何帮助将不胜感激

【问题讨论】:

    标签: javascript html onresize


    【解决方案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;
    

    【讨论】:

    • OP 要求原版
    • @DeepakDavid 是的,你能用 js 写吗?没有html?
    • 'code' document.getElementById('item1').setAttribute("data-posx","0");
    • 函数 adjustDirection() { var last_pos_x = window.screenX; return function(){ if (last_pos_x window.screenX) { document.getElementById("logo").style.backgroundImage = "url('logoLeft.png')"; } last_pos_x = window.screenX; } }; var z= 调整方向(); window.onresize = z
    • 你可以在你的评论中编辑,这样我就可以看到格式了 plz
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 2013-08-28
    相关资源
    最近更新 更多