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

做~自己de王妃 提交于 2020-01-05 07:50:28

问题


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


来源:https://stackoverflow.com/questions/5558361/javascript-change-body-id-with-css-dynamically-with-respect-to-browser-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!