如何使用CSS预加载图片?

时间:2018-07-18 16:39:04

标签: html css

我正在尝试实现此代码以预加载图像,但是它不起作用。

添加CSS:

div#preload { display: none; }

</body>标签内的页脚中:

<div id="preload">
    <img src="http://gearenergy.com/wp-content/uploads/2018/04/Home-Banner-final.jpg" width="1140px" height="500px" alt="Home-Banner_01" />
    <img src="http://gearenergy.com/wp-content/uploads/2018/04/front-page-background.jpg" width="550px" height="400px" alt="PresentationBG_02" />
    <img src="http://gearenergy.com/wp-content/uploads/2018/07/orange-color-overlay.png" width="600px" height="600px" alt="FinanceReportBG_03" />
    <img src="http://gearenergy.com/wp-content/uploads/2018/04/front-page-background-blue.jpg" width="550" height="400" alt="LatestNewsBG_04" />
</div>

很明显,我已经替换了HTML并重新指向图像,但是它仍然无法正常工作。

1 个答案:

答案 0 :(得分:1)

在这种情况下,我个人将使用JavaScript。但是,如果只需要CSS,则可以将所有图像预加载到div标签中,该标签位于窗口的隐藏部分中,如下所示:

#preload
{
    position:absolute;
    top:-9999px;
    left:-9999px;
}

<div id="preload">
    <img src="http://gearenergy.com/wp-content/uploads/2018/04/Home-Banner-final.jpg" width="1140px" height="500px" alt="Home-Banner_01" />
    <img src="http://gearenergy.com/wp-content/uploads/2018/04/front-page-background.jpg" width="550px" height="400px" alt="PresentationBG_02" />
    <img src="http://gearenergy.com/wp-content/uploads/2018/07/orange-color-overlay.png" width="600px" height="600px" alt="FinanceReportBG_03" />
    <img src="http://gearenergy.com/wp-content/uploads/2018/04/front-page-background-blue.jpg" width="550" height="400" alt="LatestNewsBG_04" />
</div>