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