按顺序滑动div

时间:2016-11-20 15:21:37

标签: jquery

我在滑块div中有一些项目,我希望每次触发跳过类的点击事件时动画左-299px,并且如果它到达它,则动画回到它的正常位置。

请问我该如何做到这一点?

我试过但它只有动画-299px并停止。

我写下了一些html,css和jquery示例:

CSS

Function.prototype.wait = function(time){
	var fn = this;
	var timeout = null;
	return function(){
		var inst = this;
		var args = arguments;
		clearTimeout(timeout);
		timeout = window.setTimeout( function(){
			var ret = fn.apply(inst,args);
 		}, time);
	};
};

HTML

<style>
.items{
    width:299px;
    height:80px;
    float:left;
    color:white;
}
.slider{
    min-width:1495px;
    height:80px;
}
.container{
    width:299px;
    height:80px;
}

.one{
background-color:red;
}
.two{
background-color:yellow;
}
.three{
background-color:red;
}

JQUERY

<a href='#' class='skip'>Skip</a>
<div class='container'>
    <div class='slider'>
        <div class='items one'>Item 1</div>
        <div class='items two'>Item 2</div>
        <div class='items three'>Item 3</div>
    </div>
</div>

2 个答案:

答案 0 :(得分:1)

您的代码设置 margin-left属性变为等于-299px。如果您希望此更改随后起作用,则必须获取先前的margin-left值,并按照您的需要继续减少该值。

幸运的是,jQuery为您省去了手动递减和支持CSS增量更改的麻烦 - 只需使用-=299px而不仅仅是-299px

$(document).on('click','.skip',function(e){
    e.preventDefault();
    $('.slider').animate({marginLeft:"-=299px"},"fast");
    //                                ^ magic

    //stop default behaviour
    return false;
});
.items{
    width:299px;
    height:80px;
    float:left;
    color:white;
}
.slider{
    min-width:1495px;
    height:80px;
}
.container{
    width:299px;
    height:80px;
}

.one{
background-color:red;
}
.two{
background-color:yellow;
}
.three{
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' class='skip'>Skip</a>
<div class='container'>
    <div class='slider'>
        <div class='items one'>Item 1</div>
        <div class='items two'>Item 2</div>
        <div class='items three'>Item 3</div>
    </div>
</div>

答案 1 :(得分:0)

var $slider = $('.slider');
$(document).on('click','.skip',function(e){
    e.preventDefault();
    
    if (parseInt($slider.css('marginLeft')) < -(299 * $slider.find('.items').length - 1)) {
      $slider.animate({marginLeft:"0px"}, "fast");
    } else {
      $slider.animate({marginLeft: "-=299px"}, "fast");
    }
});
.items{
    width:299px;
    height:80px;
    float:left;
    color:white;
}
.slider{
    min-width:1495px;
    height:80px;
}
.container{
    width:299px;
    height:80px;
}

.one{
background-color:red;
}
.two{
background-color:yellow;
}
.three{
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' class='skip'>Skip</a>
<div class='container'>
    <div class='slider'>
        <div class='items one'>Item 1</div>
        <div class='items two'>Item 2</div>
        <div class='items three'>Item 3</div>
    </div>
</div>