如何使按钮更改图像?

时间:2017-05-21 16:40:12

标签: javascript html css

我做了一个div,里面有一个图像然后我做了一个按钮。而我希望它是这样的,当我按下按钮时,它会切换多个我想要添加的图像。

以下是按钮和图片的HTML:



#gallery {
  width: 800px;
  height: 450px;
  position: absolute;
  left: 310px;
  top: 180px;
  padding: 0;
  margin: 0;
  z-index: -1;
}

#UCL {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 5px;
}

button {
  width: 100px;
  height: 60px;
  font-family: "Economica";
  font-size: 18px;
  background-color: #383838;
  color: white;
  font-weight: bold;
  font-size: 23px;
  border: 0;
  margin-left: 670px;
  margin-top: 110px;
  border-radius: 12px;
  position: absolute;
  opacity: 1;
}

button:hover {
  background-color: white;
  transition: ease 0.7s;
  color: black;
}

<button onclick="myFunction()"> 
  Next
</button>
<div id=gallery>
  <img id="UCL" src="http://byuinsider.com/wp-
    content/uploads/2015/09/Champions-League-Stadium-Football-Wallpapers-
    HD.jpg" alt="Stadium">
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

您可以使用包含图像网址的数组来执行此操作,如下所示:

#gallery {
  width: 800px;
  height: 450px;
  position: absolute;
  left: 310px;
  top: 180px;
  padding: 0;
  margin: 0;
  z-index: -1;
}

#UCL {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 5px;
}

button {
  width: 100px;
  height: 60px;
  font-family: "Economica";
  font-size: 18px;
  background-color: #383838;
  color: white;
  font-weight: bold;
  font-size: 23px;
  border: 0;
  margin-left: 670px;
  margin-top: 110px;
  border-radius: 12px;
  position: absolute;
  opacity: 1;
}

button:hover {
  background-color: white;
  transition: ease 0.7s;
  color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="myFunction()" id="nextImage"> 
  Next
</button>
<div id=gallery>
  <img id="UCL" src="" alt="Puppy">
</div>
eq = sympy.diff(sympy.diff(x(t), t), t) + w**2*x(t)

答案 1 :(得分:1)

这是一种基本的方法,应该让你开始......

imgs=["images/photo1.jpg","images/photo2.jpg","images/photo3.jpg"];
currentImg=0;
function myFunction(){
    if (currentImg<imgs.length-1){
        currentImg++
    }
    else {
        currentImg=0;
    }
    document.querySelector("#UCL").src=imgs[currentImg];
}

PS建议在学习时使用查询代替vanilla js是无稽之谈。