javascript - 如何在此脚本中设置自动 slider 功能?

标签 javascript jquery html css

我想为我的网站制作一个 slider ,它只有在我点击 .slideshow-prev.slideshow-next 时才有效。我想在不单击 prevnext 按钮的情况下自动设置此功能。

   <script>
    //an image width in pixels
    var imageWidth = 980;


    //DOM and all content is loaded
    $(window).ready(function() {

      var currentImage = 0;

      //set image count
      var allImages = $('#slideshow li img').length;

      //setup slideshow frame width
      $('#slideshow ul').width(allImages * imageWidth);

      //attach click event to slideshow buttons
      $('.slideshow-next').click(function() {

        //increase image counter
        currentImage++;
        //if we are at the end let set it to 0
        if (currentImage >= allImages) currentImage = 0;
        //calcualte and set position
        setFramePosition(currentImage);

      });

      $('.slideshow-prev').click(function() {

        //decrease image counter
        currentImage--;
        //if we are at the end let set it to 0
        if (currentImage < 0) currentImage = allImages - 1;
        //calcualte and set position
        setFramePosition(currentImage);

      });

    });

    //calculate the slideshow frame position and animate it to the new position
    function setFramePosition(pos) {

      //calculate position
      var px = imageWidth * pos * -1;
      //set ul left position
      $('#slideshow ul').animate({
        left: px
      }, 300);
    }

  </script>

最佳答案

假设您希望您的图像始终以 2 秒为间隔更改为下一张:

setInterval(function() {
    //increase image counter
    currentImage++;
    //if we are at the end let set it to 0
    if (currentImage >= allImages) currentImage = 0;
    //calculate and set position
    setFramePosition(currentImage);
}, 2000);

More about Javascript's setInterval.

关于javascript - 如何在此脚本中设置自动 slider 功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36045346/

相关文章:

javascript - 编写效果Javascript

javascript - 需要在 JQuery cookie 中保存 'this' 值

javascript - 获取月份功能不适用于 iPad

javascript - 不使用 webpack 或 browserify 将 .vue 文件编译成 .js 文件

html - 在 mvc5 应用程序的所有不同布局页面中添加元标记

php - 在我的 PHP 代码中解析错误 : Syntax error, 文件意外结束

jquery - 如何用逗号分割输入内容并将CSS应用于每个元素

javascript - Highcharts-如何删除系列数据之一的工具提示

javascript - 如何在更改时在 div 中显示范围值?

javascript - 如何使用ajax保存列表