Jquery水平幻灯片基于div宽度

时间:2015-09-24 20:58:11

标签: javascript jquery html css

我有jquery脚本,你可以点击左右按钮,它会水平滚动显示更多内容。

需要滚动的内容位于宽度为1296px的div中,但是我想设置我的jquery代码以自动获取div的宽度,当你按下其中一个向左或向右滚动按钮时将完全滚动1296px。

我想这样做,因为我需要稍后优化所有屏幕尺寸的设计,这将是更简单的方法。

我的代码:

    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%'});
    }
});

3 个答案:

答案 0 :(得分:1)

这个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。基本上我们首先计算宽度,不要反复做同样的事情,并在需要时重复使用它。

答案 1 :(得分:0)

为什么不先获取可见容器的宽度,然后再使用该值?快速举例:

var width = $('container').width();

然后在动画中:

var left = $item2.css('left') + width;
$item.animate({'left',left});

作为备注,innerWidthouterWidth可能比width更有益,具体取决于您如何设置所有内容,因此如果值不是很正确,请查看那些文件。

答案 2 :(得分:0)

我创造了一个小提琴,我认为可以解决你的问题:

http://jsfiddle.net/77bvnw3n/

我所做的是创建另一个变量(称为width),在页面加载时,动态获取容器的宽度。

var width = $('.group-container').width(); //Container Width

每当按下“下一个”或“上一个”按钮时,此变量也会重置(如果自加载页面后窗口已调整大小)。

 $('#arrowR').click(function(){
   index2++;

   //recheck container width
   width = $('.group-container').width();

   $item2.animate({'left':'-=' + width + 'px'});
});

看看,如果有帮助请告诉我。

注意:我替换了'下一步'和'以前'在我的小提琴中带有彩色框的图像,我认为你的代码中也有一个拼写错误

endIndex2 = ( $item.length )

改为:

endIndex2 = ( $item2.length )