通过 JavaScript 更改 body 标签样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11721501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Changing body tag style through JavaScript
提问by Nojan
I'm trying to write a script to change the width of the page, considering user's client width. It's something like this:
考虑到用户的客户端宽度,我正在尝试编写一个脚本来更改页面的宽度。它是这样的:
function adjustWidth() {
width = 0;
if (window.innerHeight) {
width = window.innerWidth;
} else if (document.documentElement && document.documentElement.clientHeight) {
width = document.documentElement.clientWidth;
} else if (document.body) {
width = document.body.clientWidth;
}
if (width < 1152) {
document.getElementsByTagName("body").style.width="950px";
}
if (width >= 1152) {
document.getElementsByTagName("body").style.width="1075px";
}
}
window.onresize = function() {
adjustWidth();
};
window.onload = function() {
adjustWidth();
};
With this script I get an error from Firebug:
使用此脚本,我收到来自 Firebug 的错误消息:
document.getElementsByTagName("body").style is undefined
Now my question is, how can i access the style of body? Because in the css sheet its selector and width property are defined.
现在我的问题是,如何访问 body 的样式?因为在 css 表中定义了它的选择器和宽度属性。
回答by Pointy
That function returns a list of nodes, even though there's only one <body>
.
该函数返回一个节点列表,即使只有一个<body>
.
document.getElementsByTagName("body")[0].style = ...
Now, that said, you may want to look into doing this with CSS instead of JavaScript. With CSS media queries, you make such adjustments:
现在,也就是说,您可能想考虑使用 CSS 而不是 JavaScript 来实现这一点。使用 CSS 媒体查询,您可以进行以下调整:
@media screen and (max-width: 1151px) {
body { width: 950px; }
}
@media screen and (min-width: 1152px) {
body { width: 1075px; }
}
Media queries work in IE9 and pretty much all other modern browsers. For IE8 you can fall back to JavaScript or just let the body be 100% of the viewport width or something.
媒体查询适用于 IE9 和几乎所有其他现代浏览器。对于 IE8,您可以回退到 JavaScript,或者只是让 body 为视口宽度的 100% 或其他东西。
回答by voodoo417
document.getElementsByTagName("body")[0].style
回答by Snow Blind
getElementsByTagName
returns an array of nodes so you must use []
to access elements.
getElementsByTagName
返回一个节点数组,因此您必须使用它[]
来访问元素。
Try document.getElementsByTagName("body")[0].style
尝试 document.getElementsByTagName("body")[0].style
回答by Naing Min Khant
document.getElementsByTagName('body')[0].style = 'your code';
Example:
例子:
document.getElementsByTagName('body')[0].style = 'margin-top: -70px';
回答by shannon.stewart
I believe what you get back from document.getElementsByTagName("body")
is HTMLCollection
. You should be able to use document.getElementsByTagName("body")[0].style
to get what you want.
我相信你得到的回报document.getElementsByTagName("body")
是HTMLCollection
. 你应该能够使用document.getElementsByTagName("body")[0].style
来获得你想要的。