admin管理员组

文章数量:1287513

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"
;

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 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"
;

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.

Share Improve this question asked Apr 5, 2011 at 20:51 techuser7777777techuser7777777 251 silver badge5 bronze badges 1
  • 1 Why a different ID? Why not just give it a class? Also, are you getting errors? How do you know it's not working? – Richard Marskell - Drackir Commented Apr 5, 2011 at 20:55
Add a ment  | 

4 Answers 4

Reset to default 10

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/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 patibility)

I remend using jQuery, a JavaScript library. It handles a lot of browser inpatibility. 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");
});

本文标签: javascript change body ID (with css) dynamically with respect to browser window sizeStack Overflow