【问题标题】:Delay or specified width on body needed for correct rendering正确渲染所需的延迟或指定的主体宽度
【发布时间】:2016-06-19 07:54:13
【问题描述】:

(如果有人出于娱乐目的对背景故事感兴趣,这是my previous question 的后续内容。它可能无法帮助您理解这个问题。)


这里有两个元素 <aside><main> 通过 JavaScript 获得宽度和高度,因此它们的组合宽度就是屏幕的宽度(注意它们的显示是内联块)。如果您在 Web 浏览器(最大化浏览器,以使浏览器的宽度等于屏幕的宽度)中运行此代码,您可能会注意到 body 出人意料地不适合元素:

<!DOCTYPE html>
<html>    
<body> 

<aside></aside><!-- comment to remove inline-block whitespace

--><main></main>

<script>
  var h = screen.height/100;
  var w = screen.width/100;

  var e = document.getElementsByTagName("aside")[0].style;
  e.display = "inline-block";
  e.backgroundColor = "lightblue";
  e.width = 14*w + "px";
  e.height = 69*h + "px";
  e.marginRight = 0.5*w + "px";

  e = document.getElementsByTagName("main")[0].style;
  e.display = "inline-block";
  e.backgroundColor = "green";
  e.width = 85.5*w + "px";
  e.height = 69*h + "px";   

  e = document.getElementsByTagName("body")[0].style;
  e.margin = e.padding = "0";
  e.backgroundColor = "black";
</script>
</body>
</html>

如果你给 JavaScript 一个延迟,元素会被正确渲染。这表明身体以某种方式“需要时间”来确定其正确的宽度:

<script>
  setTimeout(function() {

    [...]

  }, 200);
</script>

还可以通过添加以下行来为正文指定screen.width 的指定宽度,而不是引入延迟。这支持了之前的猜测,body 不会立即知道它的正确宽度(除非指定):

<script>

  [...]

  e.width = 100*w + "px";
</script>

尽管我冒昧地猜测来解释这一点,但我实际上并不知道发生了什么。

为什么一开始就没有正确放置元素,为什么这两种解决方案有效?


(注意: 也可以通过使用e.whiteSpace = "nowrap"; 将正文的空白设置为 nowrap 来解决此问题,但我怀疑这与其他两个不一样。而是为身体内部的元素创造空间,这只是迫使元素彼此相邻,即使身体没有足够的空间。)

【问题讨论】:

    标签: javascript html document-body


    【解决方案1】:

    在运行代码之前,您应该等待 DOM 可用,请参见此处:pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it。这可能就是 setTimeout 起作用的原因。此外,您应该为不同的元素分配单独的变量名称。

    // self executing function before closing body tag
    (function() {
       // your code here
       // the DOM will be available here
    })();
    

    您使用 Javascript 而不是 CSS 来完成这项任务有什么原因吗?我建议给你的元素 css id 即 id="aside",然后设置你的 css 样式:

    html,body {
      width: 100%;
      height: 100%;
    }
    #aside {
      display:inline-block;
      position: relative;
      float: left;
      width: 14%;
      height: 69%;
      background: blue;
    }
    #main {
      display:inline-block;
      position: relative;
      float: left;
      width: 86%;
      height: 31%;
      background: azure;
    }
    

    【讨论】:

    • 对您链接中问题的接受的答案表明,在正文末尾放置 JavaScript 就足够了,我有。
    • 回答你的第二点,我知道没有任何 CSS 可以像 JavaScript 样式一样设置 HTML 样式,以 screen.widthscreen.height 设置样式。 CSS 中的 % 指的是网络浏览器的宽度/高度,而不是屏幕。
    • 接受的答案还说要在 DOM 准备好后执行你的 js,方法是将你的代码包装在一个自执行函数中,或者像 jQuery 一样使用准备好的代码,试试看你怎么做。跨度>
    • 我现在已经更新了答案,让我知道这是否适合你。
    猜你喜欢
    • 2019-02-21
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    相关资源
    最近更新 更多