如何将下一个/上一个按钮添加到我的JavaScript(PHP / MySQL)图像滑块?

时间:2017-08-19 23:01:24

标签: javascript php mysql

我有以下代码从MySQL数据库获取图像并将它们显示在滑块中。任何人都可以告诉我如何添加下一个/上一个按钮。任何帮助将不胜感激,谢谢!

<img id="slide" src="./pics/image1.jpg" alt="slideshow" width="300" height="300">


<script>
var time = 5000,    // time between images
i = 0,              // index for changing images
images = [],    // array of img src from PHP
preloads = [],      // array of preloaded images
slide = document.getElementById("slide");


images = <?php echo json_encode($paths); ?>; // from PHP to Js array
var len = images.length;

function changeImg(){
    slide.src = preloads[i].src;
    if (++i > len-1){
        i = 0;
    }
    setTimeout(changeImg, time);
}

function preload(){
    for (var c=0; c<len; c++){
        preloads[c] = new Image;
        preloads[c].src = images[c];
    }
}
window.addEventListener("load", function(){
    preload();
    setTimeout(changeImg, time);
});

1 个答案:

答案 0 :(得分:0)

继上一个帖子How do i display images from MySQL database in a JavaScript image slider?之后,类似以下内容的作品。第一张图片被硬编码到位,因此关闭javascript的用户仍会看到第一张图片。另外,第一张图片在页面加载时可见。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Slideshow from PHP - Button Controlled</title>
<style>
p {
  width: 300px; 
  display: flex; justify-content: space-between;
}
#prev, #next {
  background: #aaa; padding: 5px; width: 6em;
  text-align: center; cursor: pointer;
}
</style>
</head>
<body>
<div>
  <img id="slide" src="./pics/image1.jpg" alt="slideshow" width="300" height="300">
  <p>
    <span id="prev">Previous</span>
    <span id="next">Next</span>
  </p>
</div>
<script>
var time = 5000,    // time between images
    i = 0,          // index for changing images
    images = [],    // array of img src from PHP
    preloads = [],  // array of preloaded images
    slide = document.getElementById("slide");

images = <?php echo json_encode($paths); ?>; // from PHP to Js array
var len = images.length;

function changeImg(dirn){
  i += dirn;
  if (i > len-1){
    i = 0;
  }
  if (i < 0) {
    i = len-1;
  }
  slide.src = preloads[i].src;
}
function preload(){
  for (var c=0; c<len; c++){
    preloads[c] = new Image;
    preloads[c].src = images[c];
  }
}
window.addEventListener("load", preload);
document.getElementById("prev").addEventListener("click", function(){
  changeImg(-1);
});
document.getElementById("next").addEventListener("click", function(){
  changeImg(1);
});
</script>
</body>
</html>