Javascript randomly adds the image from the first dom to the second div as an example


Javascript randomly adds the image in the first dom to the second div. This code is a simple example that extracts two random images from the five images in the first div and displays them in the second div.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title> Randomly display two of the five images - Test the picture with baidu space picture </title>
<script type="text/javascript">
window.onload = function (){
var count=4;
var original=new Array;//The original array
var tpDiv = document.getElementById('kstupian'); //Get the dom object
var images = tpDiv.getElementsByTagName("img");
for (var i=0;i<count;i++){original[i]=i;}
original.sort(function(){ return 0.5 - Math.random(); });
var myDiv = document.getElementById('myDiv'); //Get the dom object
for (var i=0;i<2;i++){
var bigImg = document.createElement("img"); //Create an img element
bigImg.width="200"; //You don't need to add px to 200 pixels
bigImg.src=images.item(original[i]).src; //Assign a value to the SRC attribute of the img element
myDiv.appendChild(bigImg); //Add the child element img to the dom
}

};
</script>
</head>

<body>
<h2> The first one div The pictures are five </h2>
<div id="kstupian">
<img src="http://a.hiphotos.bdimg.com/album/s%3D1000%3Bq%3D90/sign=2a369e6d918fa0ec7bc7600d16a7629f/b03533fa828ba61ee03594714134970a314e5990.jpg" width="200">
<img src="http://c.hiphotos.bdimg.com/album/s%3D1000%3Bq%3D90/sign=b03c3e4211dfa9ecf92e521752e0cc72/d058ccbf6c81800a5b37d550b13533fa838b4799.jpg" width="200">
<img src="http://h.hiphotos.bdimg.com/album/s%3D1000%3Bq%3D90/sign=a4ff82aab74543a9f11bfecc2e27b1f3/203fb80e7bec54e721374640b9389b504ec26a90.jpg" width="200">
<img src="http://g.hiphotos.bdimg.com/album/s%3D1000%3Bq%3D90/sign=cb1f8fa37b899e517c8e3e147297e242/b3119313b07eca809bdd65b9912397dda0448390.jpg" width="200">
<img src="http://a.hiphotos.bdimg.com/album/s%3D1000%3Bq%3D90/sign=fe1172bbad6eddc422e7b0fb09eb8d8c/5ab5c9ea15ce36d325dcdf6e3af33a87e850b190.jpg" width="200">
</div>
<h2> The first one div The pictures are two that are not repeated at random </h2>
<div id="myDiv" ></div>
</body>
</html>