[英]How to autoscroll horizontally with jquery
I'm trying to make horizontal scrolling effect using two buttons, left and right. 我正在尝试使用左右两个按钮来制作水平滚动效果。 But I can't sort it out.
但是我无法解决。 I managed to scroll to next element but then scrolling stops and I can't scroll to another element.
我设法滚动到下一个元素,但随后滚动停止,无法滚动到另一个元素。
$(document).ready(function(){
$("#left").click(function(){
$(".wrap").animate({scrollLeft: 0}, 1000);
return false;
});
var item_width = $('.label').outerWidth();
$("#right").click(function(){
$(".wrap").animate({scrollLeft: item_width}, 1000);
return false;
});
});
You need to keep track of your current index. 您需要跟踪当前索引。 You have shifted right once (the width of item_width), but the second time you need to animate scrollLeft: item_width*2, the third item_width*3, etc.
您已经右移了一次(item_width的宽度),但是第二次需要设置scrollLeft的动画:item_width * 2,第三个item_width * 3等。
set a variable in your document ready that starts at 0, and its incremented or decremented when you click on either right or left, and then change 0 and item_width to item_width * index 在文档中准备好一个变量,该变量从0开始,然后在单击向右或向左单击时将其递增或递减,然后将0和item_width更改为item_width * index
Uhm i'm not sure you can use "{scrollLeft: item_width}" for element different to body o window... but if you can do this change part your script: 嗯,我不确定您是否可以将“ {scrollLeft:item_width}”用于不同于窗口主体的元素...但是,如果可以这样做,请更改脚本部分:
{scrollLeft: item_width}
to 至
{scrollLeft: "+="+item_width}
JS: JS:
$(document).ready(function(){
var item_width = $('.label').css("width");
$("#left").on("click",function(){
if(parseInt($(".wrap").css("margin-left")) == 0) return;
$(".wrap").animate({marginLeft: "+="+item_width}, 1000);
return false;
});
$("#right").on("click",function(){
$(".wrap").animate({marginLeft: "-="+item_width}, 1000);
return false;
});
});
For example you can use this html: 例如,您可以使用以下html:
<div id="right">></div>
<div id="left"><</div>
<div class="wrap">
<div class="label"></div>
<div class="label"></div>
<div class="label"></div>
</div>
css: CSS:
body{
margin:0;
padding:0;
}
.wrap{
overflow:hidden;
float:left;
width:903px;
height:200px;
position:relative;
}
.label{
display:block;
float:left;
width:300px;
background-color:red;
border-left:solid 1px black;
position:relative;
height:200px;
}
#right,#left{
position:absolute;
background-color:purple;
color:white;
top:100px;
width:20px;
height:20px;
margin-top:-10px;
text-align:center;
line-height:20px;
display:block;
z-index:2;
cursor:pointer
}
#right{
right:0;
}
see the example here: http://jsfiddle.net/u3hB8/4/ 请参阅此处的示例: http : //jsfiddle.net/u3hB8/4/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.