简体   繁体   中英

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. 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.

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

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.

   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();
       });

    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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