javascript - 基于div宽度的jquery水平滑动

标签 javascript jquery html css

我有 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/

相关文章:

javascript - bootstrap 复选框按钮事件传播问题

javascript - 单个字符串到数组 JavaScript

javascript - html 的跨浏览器替代方案 = $ ('html' )

jquery - 在 Javascript 的 for 循环中分配点击处理程序

javascript - 如何使用 Jquery 在一个列标题下包含 2 列

javascript - Bootstrap 3 弹出窗口显示一个并隐藏其他不起作用

javascript - 如何检测浏览器控制台/检查器是否*打开*?

javascript - 在返回 ajax 值时隐藏按钮

jquery - 居中对齐面板并使用 bootstrap 和 css 更改其标题和主体颜色

html - 将多个 div 组合并对齐到一个形状中