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
4 Answers
Reset to default 10Here 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
版权声明:本文标题:javascript change body ID (with css) dynamically with respect to browser window size - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741287305a2370345.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论