我有 jquery 脚本,您可以在其中单击左右按钮,它会水平滚动以显示更多内容。
需要滚动的内容位于宽度为 1296px 的 div 中,但我想将我的 jquery 代码设置为自动获取 div 的宽度,当您按下向左或向右滚动按钮之一时它将精确滚动 1296 像素。
我想这样做是因为我需要稍后针对所有屏幕尺寸优化设计,这会是更简单的方法。
我的代码:
var $item2 = $('div.group'), //Cache your DOM selector
visible2 = 1, //Set the number of items that will be visible
index2 = 0, //Starting index
endIndex2 = ( $item.length ); //End index
$('#arrowR').click(function(){
index2++;
$item2.animate({'left':'-=1296px'});
});
$('#arrowL').click(function(){
if(index2 > 0){
index2--;
$item2.animate({'left':'+=18.5%'});
}
});
最佳答案
这个 Javascript 应该可以工作:
var $item2 = $('div.group'), //Cache your DOM selector
visible2 = 1, //Set the number of items that will be visible
index2 = 0, //Starting index
endIndex2 = ( $item2.length ); //End index
var w = $("#group").width();
$('#arrowR').click(function(){
index2++;
$item2.animate({'left':'-=' + w + 'px'});
});
$('#arrowL').click(function(){
if(index2 > 0){
index2--;
$item2.animate({'left':'+=' + w + 'px'});
}
});
检查这个fiddle .基本上我们最初计算宽度是为了不重复做同样的事情,并在我们需要的时候重复使用它。
关于javascript - 基于div宽度的jquery水平滑动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32770789/