[英]Javascript simple image slider
我想有一個簡單的圖片slider。那個slider應該在網址的header之間切換,應該有一個小延遲。 我希望它簡單並將圖片命名為 1.jpg、2.jpg 等,它們位於文件夾“bilder”中。
我試了一下,這是我的結果:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script type="text/javascript">
function picture_slider(){
setInterval( switch_picture(), 3000 );
return false;
}
function switch_picture() {
for ( var i = 1; i < 7 ; i++ ) {
var pfad = "bilder/" + i + ".jpg";
document.getElementById("bild").src = pfad;
i++;
};
return false;
}
</script>
</head>
<body onload="picture_slider();">
<img id="bild" src="" />
</body>
</html>
我想,我做錯了什么,因為我的瀏覽器只顯示一張圖片並且沒有切換。
在每個循環中,您都要遍歷所有圖像( for
循環),從而生成最新的圖像。 也只能使用switch_picture
(而不是switch_picture()
)。
PS:為此計數器創建一個0.jpg
圖像:
function picture_slider(){
setInterval( switch_picture, 2000 ); // corrected removing "()"
}
var bild = document.getElementById("bild")
var i = 0; // Start from image 0.jpg
function switch_picture() { // don't iterate a loop in here!
bild.src = "bilder/"+ (i++ % 7) +".jpg";
}
我在這里找到了一些東西: Stackoverflow鏈接
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script type="text/javascript">
var i = 0;
var images = [ "1", "2", "3", "4", "5", "6", "7"]
function picture_slider(){
setInterval( switch_picture, 2000 );
}
function switch_picture() {
i++;
if ( i >= images.length ) {
i = 0;
};
var bild = document.getElementById("bild");
bild.src = "bilder/" + images[i] + ".jpg";
}
</script>
</head>
<body onload="picture_slider();">
<img id="bild" src="" />
</body>
</html>
// 1. images need to store in an Array const images = [ "img/pic-1.jpg", "img/pic-2.jpg", "img/pic-3.jpg", "img/pic-4.jpg", "img/pic-5.jpg", "img/pic-6.jpg", "img/pic-7.jpg" ]; // 7. getElementById by calling, store globally (do not call inside loop/setInterval performance will loose) const imgElement= document.getElementById("slider-image"); // 2. set initial value for array index let imgIndex = 0; // 3. create setInterval() const sliderInterval = setInterval(() => { // 6. check condition if length is finished then start again from 0 if (imgIndex >= images.length) { // use >= because index start from 0 and length start from 1, if use just > then last element will be undefined imgIndex = 0; } // 5. testing // console.log(imgIndex); // 9. Dynamically change image src const imgUrl = images[imgIndex]; imgElement.setAttribute('src', imgUrl); // 4. increase value by 1 imgIndex++; }, 1000);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.