简体   繁体   English

基于浏览器宽度的问题定位元素

[英]Problems positioning element based on browser width

I have a fixed position div that I want to have position left: 0 when the browser window is smaller than 1200px, but no left positioning when larger than 1200px. 我有一个固定的位置div,我希望它的位置为左:浏览器窗口小于1200px时为0,但大于1200px时不向左定位。 I'm using this code 我正在使用此代码

var $window = $(window);
function checkWidth() {
    var windowsize = $window.width();
    document.write(windowsize);
    if (windowsize < 1200) {
        document.getElementById("DBCIbox").style.left = "0";
    } else {50
        document.getElementById("DBCIbox").style.left = "500px";
    }
}
checkWidth();
$(window).resize(checkWidth);

but it doesnt seem to be doing anything. 但它似乎没有做任何事情。 I'm setting the left=500px as simply a test to get the javascript working, then I'll worry about where I want to position it. 我将left = 500px设置为一个简单的测试,以使javascript正常工作,然后我担心要在哪里放置它。

I've done some googleing and from what I can tell this should work, what am I missing? 我已经做了一些谷歌搜索,从我可以告诉它应该工作,我想念什么?

If theres a way to clear the left positioning I'd like to know that as well. 如果有办法清除左侧位置,我也想知道。

var $window = $(window);

That line is cacheing that instance of window. 该行正在缓存该窗口实例。 You need to re-evaluate $(window) everytime you call this code to get updated width and height values 您需要在每次调用此代码时重新评估$(window)以获得更新的宽度和高度值

Updated code below 下面更新了代码

function checkWidth() {
    var $window = $(window);
    var windowsize = $window.width();
    document.write(windowsize);
    if (windowsize < 1200) {
        document.getElementById("DBCIbox").style.left = "0";
    } else {50
        document.getElementById("DBCIbox").style.left = "500px";
    }
}

checkWidth();

$(window).resize(checkWidth);

@Jnatalzia had it right, I needed to make a few tweaks, and the comments wouldn't let me post the code, but credit goes to @Jnatalzia for the answer. @Jnatalzia正确,我需要进行一些调整,并且注释不允许我发布代码,但是值得一提的是@Jnatalzia。

   function checkWidth() {
        var $window = $(window);
        var windowsize = $window.width();
        var position;       
        if (windowsize < 1390) {
            document.getElementById("DBCIbox").style.marginLeft = 0 + "px";
        } else if (windowsize >= 1390) {
            position = windowsize - 1060;
        position = position / 2;
        position = position - 175;
            document.getElementById("DBCIbox").style.marginLeft = position + "px";
        }
    }

    $("document").ready(function(){

       $(window).load(function(){
          checkWidth();
       });

       $(window).resize(function(){
          checkWidth();
       });

    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM