简体   繁体   中英

Setting styles with JavaScript before rendering

I have a list of images that are shown in a div each. The width of the divs will vary since they are specified as a percentage of their containers. The objective of that is to get a flexible design.

The images are wider than their containing divs, but all images do not have the same width. I would like to shift the images by setting a negative margin-left on the images, and in that way center the images in their containers.

Since the negative margins will depend on the width of the image, I need to check the width before setting the margins.

function marginsOfImages() {
    var images = document.getElementsByTagName('img');
    for (i = 0; i < images.length; i++) {
        var parent = images[i].parentNode;
        var parentWidth = window.getComputedStyle(parent, null).getPropertyValue("width");
        /*In order to remove the "px" from the style: */
        var indexOfPx = parentWidth.search("px");
        parentWidth = parseInt(parentWidth.substring(0, indexOfPx));
        var imageWidth = window.getComputedStyle(images[i], null).getPropertyValue("width");
        indexOfPx = imageWidth.search("px");
        imageWidth = parseInt(imageWidth.substring(0, indexOfPx));
        var value = parentWidth + 90; //Want to shift the image 90px to the left
        if (imageWidth > value) {
            images[i].style.marginLeft = (value * (-1)).toString() + "px";
        }
    }
}
window.onload = marginsOfImages;

The problem is that the images are rendered without any margin at first, and then after a second or so they will get a margin depending on their width when the JavaScript has finished; the appearance of the images will change after the page apparently has already loaded.

How can I set the correct margins before showing anything of the images? I need to load all images before determining their dimensions, right?

I'm with @Prescott in that adding a class that displays the images is probably the way to go. A more generic approach, however, is to add a "js-loaded"-class to the html element and then you can always use that. I also always use a "js" or "no-js"-class to style differently as well:

<script>
    var html = document.getElementsByTagName('html')[0];

    html.className = html.className.replace('no-js', 'js');

    window.onload = function () {
        html.className += ' js-loaded';
    };
</script>

And then you could simply:

<style>
    html.js #images img {visibility: hidden}
    html.js-loaded #images img {visibility: visible}
</style>

您可以将所有图像设置为具有visibility:hidden (或display:none )样式,然后在您的 javascript 中删除该 css 属性(或类),以便在应用边距后显示

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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