繁体   English   中英

如何使按钮更改图像?

[英]How can I make a button change images?

我做了一个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> 

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

 var images=['http://placeskull.com/300x300','http://placeskull.com/400x400','http://placeskull.com/500x500']; var idx=0; // we're at the first image so, 0 function myFunction() { $('#UCL').attr('src',images[idx]); idx=(idx+1)%(images.length); // to avoid the index getting bigger than the number of images, we use the modulo operator % to make it circular, 0 1 2 0 1 2 0 1 2 ... } myFunction(); window.setInterval(function(){ myFunction(); }, 2000); // 2000ms, change to whatever timing you want 
 #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> 

这是一种基本的操作方法,应该可以让您入门...

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建议在仍然无聊时使用查询而不是普通js。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM