首页 > 解决方案 > 根据屏幕大小重新定位元素

问题描述

我需要根据浏览器大小在页面上放置一个元素。我无法隐藏和显示此元素,因为它只能在 dom 中出现一次。看起来很简单,但我被卡住了。它似乎在部分工作。我需要做某种分离/附加吗?抱歉,我已经有一段时间没有修改普通的 JS 了。

srPos();
window.onresize = srPos();

function srPos() {
    var ww = window.innerWidth,
        sr = document.getElementById("gcs-box"),
        pp = document.getElementById("primary-panel"),
        sp = document.getElementById("secondary-panel");
    
    if (ww > 991) {
        sp.prepend(sr);
    } else {
        pp.prepend(sr);
    }        
}

我错过了什么?

标签: javascript

解决方案


您正在将返回的值srPos而不是函数本身分配给onresize属性。

删除括号:

srPos();
window.onresize = srPos;

function srPos() {
    var ww = window.innerWidth,
        sr = document.getElementById("gcs-box"),
        pp = document.getElementById("primary-panel"),
        sp = document.getElementById("secondary-panel");
    
    if (ww > 991) {
        sp.prepend(sr);
    } else {
        pp.prepend(sr);
    }        
}

推荐阅读