无法使用jquery滑动div内容

时间:2012-08-05 09:27:51

标签: jquery html css css3 slider

我正试图将div中的图像逐个向左移动。但是我只能在点击按钮时移动一个图像。我想在div中滑动图像。 这是我在jsfiddle上的代码。 http://jsfiddle.net/K2JBg/

1 个答案:

答案 0 :(得分:2)

jsFiddle demo

  • 一旦你到达最后一张图像,就可以将滑块转到起始位置,所以让我们使用 Modulus 将我们的计数器变为'0'。
  • 只需移动滑块做一些基本的数学运算:-300px * the current Counter value

每次点击后计数器都会增加,但一旦达到图片数量4,它就会跳回到值0 - 300px * 0 = 0,这会将您的图库滑回'0px ' 剩下。

jQuery的:

var imgN = $('#slide div img').length; // number of images
var c = 0; // just a Counter
$("#btn").click(function() {
    c = ++c % imgN;      // once it reaches the imgN will turn to '0'
    $("#slide div").animate({left: -300*c }, "fast");   // let's use our math!
});

修改后的CSS:

    #slide{
        height: 300px;
        width:300px;
        overflow: hidden;
        position:relative;
    }
    #slide div{
        position: absolute;
        left: 0px;
        top:0px;
        width:9000px;    /*make sure to have a big value here if you don't want to do it dynamically with jQUery*/
    }
   #slide img{
        vertical-align: top;
        height: 300px;
        width: 300px;
        float:left;
    }