在固定位置显示随机图像

时间:2016-05-14 11:39:41

标签: javascript

我有3张图片。我想要做的是当我点击图像中的任何一个时,应该在div上显示随机图像。 这是代码。请帮助。



var iarr=["1.jpg","2.jpg","3.jpg"];
function select()
{
  var random=Math.floor(Math.Random()*3);
  document.getElementById('disp').innerHTML = iarr[random];
}

<html>
<body>
  <h4> MAKE A CHOICE </h3>
  <img id='x' onclick="select" src='1.jpg'/>
  <img id='y' onclick="select" src='2.jpg'/>
  <img id='z' onclick="select" src='3.jpg'/>
  <div id='disp'/>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

var iarr=["1.jpg","2.jpg","3.jpg"];
function select(){
    var random = Math.floor(Math.random() * iarr.length);
    var div = document.getElementById('disp');
    var image = "<img src=\"" + iarr[random] + "\"/>";
    div.innerHTML = image;
}

<html>
<body>
  <h4> MAKE A CHOICE </h4>
  <img id='x' onclick="select()" src='1.jpg'/>
  <img id='y' onclick="select()" src='2.jpg'/>
  <img id='z' onclick="select()" src='3.jpg'/>
  <div id='disp'/>

工作示例:https://jsfiddle.net/pndtdt7t/

答案 1 :(得分:0)

var iarr = [
  "http://www.wallpapers-for-desktop.com/desktopbilder_for_free/free_desktopbild.jpg",
  "http://wikiin.com/media/images/15/04/21/cfe0fdfb23.jpg",
  "http://data.whicdn.com/images/89382997/large.jpg"

];

function select() {

  var img = "<img src=\""+iarr[Math.floor(Math.random() * iarr.length)]+ "\" />";

  document.getElementById('disp').innerHTML = img;
}
<html>

<body>
  <h4> MAKE A CHOICE </h3>
  <img id='x' onclick="select()" src='1.jpg'/>
  <img id='y' onclick="select()" src='2.jpg'/>
  <img id='z' onclick="select()" src='3.jpg'/>
  <div id='disp'/>