javascript 以px为单位设置主体宽度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5769385/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:17:13  来源:igfitidea点击:

set body width in px?

javascript

提问by clarkk

how can you set the body width in px in javascript?

如何在javascript中以px为单位设置主体宽度?

has to work in chrome, ff and our beloved ie

必须在 chrome、ff 和我们心爱的 ie 中工作

edit:

编辑:

it has to be used when a dialog box pops up and the horisontal scrollbar is hidden.. then I have to compensate for the missing 16px.. else the whole site is moving slightly to the right

必须在弹出对话框并且隐藏水平滚动条时使用它.. 然后我必须补偿缺失的 16px.. 否则整个网站会稍微向右移动

maybe you have better solution to the problem? I don't know :)

也许你有更好的解决方案?我不知道 :)

回答by maerics

document.body.style.width = '800px';

[Edit]

[编辑]

If you need to adjust from the existing width, per your edit, you could do something like this:

如果您需要根据现有宽度进行调整,根据您的编辑,您可以执行以下操作:

var adjustBodyWidth = function(nPixels) {
  var m, w = document.body.style.width || document.body.clientWidth;
  if (m=w.match(/^(\d+)px$/)) {
    document.body.style.width = (Number(m[1]) + nPixels) + 'px';
  }
};

回答by Pekka

If the problem is the scroll bar coming up and disappearing depending on the page's contents, I would consider forcing the page to display a (disabled) scroll bar even when there's nothing to scroll. This can be done through CSS:

如果问题是滚动条根据页面内容出现和消失,我会考虑强制页面显示(禁用)滚动条,即使没有任何内容可滚动。这可以通过 CSS 来完成:

body { overflow-y: scroll }

it works in all major browsers. It doesn't in IE, but that doesn't matter because IE shows the desired behaviour automatically.

它适用于所有主要浏览器。它在 IE 中没有,但这并不重要,因为 IE 会自动显示所需的行为。