gpt4 book ai didi

JavaScript:单击按钮后将图像加载到div中

转载 作者:太空宇宙 更新时间:2023-11-04 13:40:21 25 4
gpt4 key购买 nike

我有一个隐藏的 div(通过使用最大高度和过渡),当我单击一个按钮时它会显示出来。此 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>

最佳答案

我建议在 img 标签上使用一个属性来存储预期的 src 属性,然后将其应用于按钮点击。这将避免在您的 JavaScript 中维护 src url 列表。

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');
}
}
.class1 {
max-height:0px;
transition:max-height 1s;
overflow:hidden;
}
<button onclick="show()">Show Images</button>
<hr>

<div id="id1" class="class1">
<img data-src="https://picsum.photos/400/200" alt="">
<img data-src="https://picsum.photos/400/200" alt="">
<img data-src="https://picsum.photos/400/200" alt="">
<img data-src="https://picsum.photos/400/200" alt="">
</div>

<hr>

关于JavaScript:单击按钮后将图像加载到div中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38611291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com