Tan*_*sis 2 html javascript load image web
我有一个隐藏的div(通过使用max-height和transition),当我点击一个按钮时出现.此div包含多个第一次加载站点时加载的图像.当我点击按钮显示div时,我希望它们加载,以使网站更轻.
<!DOCTYPE html>
<html>
<head>
<style>
.class1 {
max-height:0px;
transition:max-height 1s;
overflow:hidden;
}
</style>
<script>
function show() {
document.getElementById('id1').style.maxHeight = "200px";
}
</script>
</head>
<body>
<button onclick="show()">Show Images</button>
<hr>
<div id="id1" class="class1">
<img src="img1.jpg" alt="">
<img src="img2.jpg" alt="">
<img src="img3.jpg" alt="">
<img src="img4.jpg" alt="">
</div>
<hr>
</body>
</html>Run Code Online (Sandbox Code Playgroud)
Joe*_*Joe 10
我建议使用img标签上的属性来存储预期的src属性,然后将其应用于按钮单击.这样可以避免在JavaScript中维护src url列表.
HTML
<button onclick="show()">Show Images</button>
<hr>
<div id="id1" class="class1">
<img data-src="http://lorempixel.com/400/200" alt="">
<img data-src="http://lorempixel.com/400/200" alt="">
<img data-src="http://lorempixel.com/400/200" alt="">
<img data-src="http://lorempixel.com/400/200" alt="">
</div>
<hr>
Run Code Online (Sandbox Code Playgroud)
JS
function show() {
document.getElementById('id1').style.maxHeight = "200px";
var images = document.querySelectorAll("#id1 img");
for(var i = 0; i < images.length; i++)
{
images[i].src = images[i].getAttribute('data-src');
}
}
Run Code Online (Sandbox Code Playgroud)
代码笔 - http://codepen.io/anon/pen/KrZvpJ