开发者

javascript change body ID (with css) dynamically with respect to browser window size

Here is what I have, but it is not working:

 if(window.width() < 1000)
document.getElementsByTagName('body')[0].id="be"
else
document.getElementsByTagName('body')[0].id="bd"
;
开发者_StackOverflow社区

Please tell me what I am writing wrong. Please don't tell other solutions, please just fix this code.

Basically, I want to give a different ID to the BODY tag of a website if the browser window size is less than 1000px.


Here you go:

document.body.id = window.innerWidth < 1000 ? 'be' : 'bd';

Place this code at the bottom of your page:

<script>
    function setBodyId() {
        document.body.id = window.innerWidth < 1000 ? 'be' : 'bd';
    }           
    window.onload = setBodyId;
    window.onresize = setBodyId;
</script>

Live demo: http://jsfiddle.net/simevidas/THqXB/


You can do this with javascript but the optimal solution is to use CSS Media Queries for such scenarios.

see > CSS Media Queries as Browser Resizes?


window.width() is not a function. Use window.innerWidth or window.outerWidth instead. (check browser compatibility)


I recommend using jQuery, a JavaScript library. It handles a lot of browser incompatibility. For example, innerWidth and outerWidth properties are not supported in IE.

This will work cross browser:

$(function(){
    $("body").attr("id", $(window).width() < 1000 ? "be" : "bd");
});

If you want it to change as the window resizes, you need to add an event listener to the window resize event:

$(window).resize(function(){
    $("body").attr("id", $(this).width() < 1000 ? "be" : "bd");
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜