简体   繁体   English

如何在渲染前修改窗口调整大小事件中的 CSS?

[英]How to modify CSS in window resize event before rendering?

I have two DIV elements with style="float:left;"我有两个带有style="float:left;"的 DIV 元素. . I set the margin, width, etc. based on the size of the window.我根据窗口的大小设置边距、宽度等。 When the window is smaller I lower the width and margin CSS attribute values of the DIVs to make them appear next to each other (not below).当窗口较小时,我会降低 DIV 的宽度和边距 CSS 属性值,以使它们彼此相邻(不在下方)。

This looks nice in Firefox, however in Chrome and Opera the DIVs jump below each other for a moment before my JavaScript runs.这在 Firefox 中看起来不错,但是在 Chrome 和 Opera 中,DIV 会在我的 JavaScript 运行之前相互跳动一会儿。 After a moment the screen looks nice again.片刻之后,屏幕又好看了。

The question: Is there a way to catch a window.onresize event and manipulate CSS before the effects of the resize event are visible on the browser?问题:有没有办法在 resize 事件的效果在浏览器上可见之前捕获window.onresize事件并操作 CSS?

You could use media-queries.您可以使用媒体查询。 These are the prefered method for responsive design.这些是响应式设计的首选方法。

CSS CSS

 div {
        margin-left: 20px;
    }

    @media (max-width: 600px) {
      div {
        margin-left: 5px;
      }
    }

In this example the div will have a margin-left of 5px on screens that are 600px in width or lower.在此示例中,div 在宽度为 600 像素或更低的屏幕上将具有 5 像素的margin-left This is part of your CSS so no waiting for things to load, it loads with the rest of your CSS.这是您的 CSS 的一部分,因此无需等待加载,它会与您的其余 CSS 一起加载。

This is because Firefox waits for javascript to load before rendering the page.这是因为 Firefox 在呈现页面之前会等待 javascript 加载。 Chrome and Opera display the page, regardless of whether javascript has loaded or not. Chrome 和 Opera 显示页面,无论是否加载了 javascript。 Try writing javascript to set the effected body to visibility: hidden;尝试编写javascript将受影响的主体设置为visibility: hidden; initially, and changing it to "visibility: visible;"最初,并将其更改为“可见性:可见;” after the javascript has executed. javascript执行后。

Update:更新:

Set visibility: hidden;设置visibility: hidden; in the css.在 CSS 中。

And add this inside of your <head></head> :并将其添加到您的<head></head>中:

<noscript>
    body { visibility: visible; }
</noscript>

This will ensure the body is invisible until the javascript has loaded.这将确保在加载 javascript 之前正文是不可见的。 In the case that javascript isn't enabled for the device, it defaults to visibility: visible;如果设备未启用 javascript,则默认为visibility: visible; . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM