javascript change body ID (with css) dynamically w

2019-07-28 05:15发布

问题:

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.

回答1:

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/



回答2:

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?



回答3:

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



回答4:

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