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

时间:2016-07-27 11:10:16

标签: javascript html image web load

我有一个隐藏的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>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:10)

我建议使用img标签上的属性来存储预期的src属性,然后将其应用于按钮单击。这样可以避免在JavaScript中维护src网址列表。

<强> HTML

namespace1::setVarname1 $val
namespace1::getVarname1

<强> JS

<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>

代码笔 - http://codepen.io/anon/pen/KrZvpJ

答案 1 :(得分:1)

这是工作小提琴https://jsfiddle.net/6ve7ub79/

您可以使用jQuery轻松完成

<强>的jQuery

$(document).ready(function(){
$('button').bind('click', function(){
$('.i1').attr('src', 'img1.jpg');
$('.i2').attr('src', 'img2.jpg');
$('.i3').attr('src', 'img3.jpg');
$('.i4').attr('src', 'img4.jpg');
});
});

<强> HTML

<button onclick="show()">Show Images</button>
<hr>
<div id="id1" class="class1">
<img class="i1" src="" alt="">
<img class="i2" src="" alt="">
<img class="i3" src="" alt="">
<img class="i4" src="" alt="">
</div>
<hr>

<强> CSS

.class1 {
  transition:max-height 1s;
}

答案 2 :(得分:0)

试试这段代码

<!DOCTYPE html>
<html>
<head>
  <style>
    .class1 {
      max-height:0px;
      transition:max-height 1s;
      overflow:hidden;
    }
  </style>
  <script>
    function show() {
      document.getElementById('id1').innerHTML= '<img src="img1.jpg" alt=""><img src="img2.jpg" alt=""><img src="img3.jpg" alt=""><img src="img4.jpg" alt="">';
      document.getElementById('id1').style.maxHeight = "200px";
    }
  </script>
</head>
<body>
  <button onclick="show()">Show Images</button>
  <hr>

  <div id="id1" class="class1">

  </div>

  <hr>
</body>
</html>

答案 3 :(得分:0)

<!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>