简体   繁体   English

如何在window.load之前获得计算出的CSS样式?

[英]How to get a computed CSS style before window.load?

I've got a custom slideshow page with hundreds of large pictures in markup. 我有一个自定义的幻灯片页面,其中包含数百张标记的大图片。 In addition, there is an adjustment to the layout that can't be done with CSS alone, and requires javascript. 另外,对于布局的调整是单靠CSS无法完成的,并且需要javascript。 That adjustment depends on the computed CSS styles of a couple page elements. 该调整取决于几个页面元素的计算CSS样式。

Here's the issue: getting a computed CSS style on (document).ready doesn't seem to work. 这是问题:在(document).ready上获得计算的CSS样式似乎不起作用。 That makes perfect sense, because layout/paint haven't occurred yet when the DOM is merely registered. 这是完全合理的,因为在仅仅注册DOM时尚未发生布局/绘制。

(window).load is the obvious answer here. (window).load是这里明显的答案。 But the waiting period for (window).load is maddeningly long in this case, because it takes literally 30 seconds (longer on slow connections!) for all the 100+ large images to be downloaded. 但是在这种情况下, (window).load的等待时间非常长,因为对于所有要下载的100多个大图像,它需要30秒(慢速连接时间更长!)。 That's fine in principle for the slideshow, because the slideshow starts being usable once the first two images are loaded, long before all the images are loaded. 原则上幻灯片放映很好,因为在加载前两个图像之前,幻灯片开始可用,远在所有图像加载之前。 The thing is, I'd like the scripted CSS layout correction to occur at that point as well. 问题是,我希望脚本化的CSS布局校正也在那时发生。

To check for imgs being loaded, I'm use imageLoaded , which is great, and gets around the issues with jquery's load event when used with imgs. 要检查正在加载的imgs,我使用的是imageLoaded ,这很棒,并且当与imgs一起使用时可以解决jquery的load事件的问题。 But how do I check for "load"-like events (and the availability of computed styles) on a page element, for example a div? 但是,如何检查页面元素上的“加载”类事件(以及计算样式的可用性),例如div? (I realize divs don't fire load events.) In principle, is there a reliable cross-browser DOM event in between (document).ready and (window).load that I can listen for on a particular set of elements, to get computed styles? (我意识到div不会触发加载事件。)原则上,在(document).ready(window).load之间是否存在可靠的跨浏览器DOM事件,我可以在一组特定的元素上监听,得到计算样式? Or am I forced to choose between these two temporal extremes? 或者我被迫在这两个时间极端之间做出选择?

On CSS load 关于CSS加载

Source: https://stackoverflow.com/a/12570580/1292652 资料来源: https //stackoverflow.com/a/12570580/1292652

Add a unique reference styles to the CSS files you want to check for like so: 为要检查的CSS文件添加唯一的引用样式,如下所示:

#ensure-cssload-0 {
  display: none;
}

Then, use a JS function, cssLoad() , to repeatedly check whether the CSS has been downloaded (not sure if this is significantly different from when the CSS is actually painted/rendered): 然后,使用JS函数cssLoad()重复检查是否已下载CSS(不确定这是否与实际绘制/渲染CSS时有很大不同):

var onCssLoad = function (options, callback) {
    var body = $("body");
    var div = document.createElement(constants.TAG_DIV);
    for (var key in options) {
        if (options.hasOwnProperty(key)) {
            if (key.toLowerCase() === "css") {
                continue;
            }
            div[key] = options[key];
        }
    }

    var css = options.css;
    if (css) {
        body.appendChild(div);
        var handle = -1;
        handle = window.setInterval(function () {
            var match = true;
            for (var key in css) {
                if (css.hasOwnProperty(key)) {
                    match = match && utils.getStyle(div, key) === css[key];
                }
            }

            if (match === true) {
                window.clearTimeout(handle);
                body.removeChild(div);
                callback();
            }
        }, 100);
    }
}

You can use it as: 您可以将其用作:

onCssLoad({
    "id": <insert element CSS applies to>,
     css: <insert sample CSS styles>
}, function () {
    console.log("CSS loaded, you can show the slideshow now :)");
});


On CSS computation 关于CSS计算

Source: http://atomicrobotdesign.com/blog/javascript/get-the-style-property-of-an-element-using-javascript/ 资料来源: http //atomicrobotdesign.com/blog/javascript/get-the-style-property-of-an-element-using-javascript/

The previous solution only told if a CSS file had been 'downloaded' , while in your question you mention you need to know when a style for an element has been 'computed' or 'rendered' or 'painted' . 之前的解决方案仅告知CSS文件是否已被“下载” ,而在您提出的问题中,您需要知道元素的样式何时被“计算”“渲染”“绘制” I hope this might resolve that. 我希望这可以解决这个问题。

Add a unique reference styles to the CSS files you want to check for like so: 为要检查的CSS文件添加唯一的引用样式,如下所示:

#ensure-cssload-0 {
  ignored-property: 'computed';
}

Now, use getPropertyValue and getComputedStyle to check for the CSS: 现在,使用getPropertyValuegetComputedStyle来检查CSS:

function getStyle(elem, prop) {
    return window.getComputedStyle(elem, null).getPropertyValue(prop);
}

Now, just use a while loop with a callback: 现在,只需使用带回调的while循环:

function checkStyle(elem, prop, callback) {
    while ( getStyle(elem, prop) !== 'computed' ) {
        // see explanation below
    }
    callback()
}

Since JavaScript doesn't have a pass statement ( like in Python ), we use an empty code block. 由于JavaScript没有pass语句比如Python ),我们使用空代码块。

If you want to retrieve all the CSS styles applied to an element ( warning: this will also show inherited styles), check out this SO answer . 如果要检索应用于元素的所有 CSS样式( 警告:这也将显示继承的样式),请查看此SO答案


Avoiding the while() loop 避免while()循环

Using while loops to check for anything is usually NOT recommended as it 通常不建议使用while循环来检查任何内容 hangs uo the browser 挂起浏览器 doesn't let the JavaScript thread do anyting else (all browsers nowadays are multithreaded, see this comic ). 不让JavaScript线程做任何其他事情(现在所有浏览器都是多线程的,请看这个漫画 )。

Here's Chuck suggested , this solution is much better: 这是Chuck建议的 ,这个解决方案要好得多:

function checkStyle(elem, prop, callback) {
    if ( getStyle(elem, prop) !== 'computed' ) {
        // see explanation below
        window.setTimeout( function() {checkStyle(elem, prop, callback);}, 100 )
    } else {
        callback()
    }
}

This is much better. 这要好得多。 Now the function asynchronously checks every 100ms (you can change this value if you want). 现在该函数每隔100ms异步检查一次(如果需要,可以更改此值)。 The wrapping of the function while setting the timeout was necessary as setTimeout() doesn't allow passing of any arguments yet. 设置超时时包装函数是必要的,因为setTimeout()不允许传递任何参数。

Hope this helped. 希望这有帮助。 See the source code of this post for some more links... 有关更多链接,请参阅此帖子的源代码......

You can use DOMContentLoaded event. 您可以使用DOMContentLoaded事件。 It fires when dom tree is ready and styles applyed. 当dom树准备好并且使用样式时它会触发。 window.load fires, when all images and scripts loaded. 加载所有图像和脚本时,window.load会触发。

if you using jQuery, you can use this: 如果你使用jQuery,你可以使用这个:

$(function(){
 // this fn not waiting for images
  $('.selector-class')[0].style ;// this is your computed style OR...
  $('.selector-class').css(); // json representation of style;
});

if you have no jQuery on page ... in modern browsers you can use this code: 如果页面上没有jQuery ...在现代浏览器中,您可以使用以下代码:

document.addEventListener( "DOMContentLoaded", function(){
  var computedStyle = document.querySelector('#yourElementId').style ; 
})

YatharthROCK Addedd very precission solution below. YatharthROCK在下面添加了非常精确的解决方案。

My other answer 我的另一个答案 only told you when a CSS file had been downloaded , while in your question you mention you need to know when a style for an element has been computed or rendered or painted - 只有在下载 CSS文件时告诉你,而在你的问题中你提到你需要知道元素的样式何时被计算渲染绘制 - has been updated. 已经升级。

I hope this addresses the issue (I didn't want to merge this with the other answer as I felt it attacked a different angle...) 我希望这能解决这个问题(我不想将其与其他答案合并,因为我认为它攻击的角度不同......) I changed my mind, see the edit. 我改变主意,看到编辑。

Source: http://atomicrobotdesign.com/blog/javascript/get-the-style-property-of-an-element-using-javascript/ 资料来源: http //atomicrobotdesign.com/blog/javascript/get-the-style-property-of-an-element-using-javascript/

Add a unique reference styles to the CSS files you want to check for like so: 为要检查的CSS文件添加唯一的引用样式,如下所示:

#ensure-cssload-0 {
  ignored-property: 'computed';
}

Now, use getPropertyValue and getComputedStyle to check for the CSS: 现在,使用getPropertyValuegetComputedStyle来检查CSS:

function getStyle(elem, prop) {
    return window.getComputedStyle(elem, null).getPropertyValue(prop);
}

Now, just use a while loop with a callback: 现在,只需使用带回调的while循环:

function checkStyle(elem, prop, callback) {
    while ( getStyle(elem, prop) !== 'computed' ) {
        // see explanation below
    }
    callback()
}

Since JavaScript doesn't have a pass statement ( like in Python ), we use an empty code block. 由于JavaScript没有pass语句比如Python ),我们使用空代码块。

If you want to retrieve all the CSS styles applied to an element ( warning: this will also show inherited styles), check out this SO answer 如果要检索应用于元素的所有 CSS样式( 警告:这也将显示继承的样式),请查看此SO答案

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

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