CSS3 /带有可变宽度子元素的无限垂直滚动轮播

时间:2019-03-07 19:17:46

标签: jquery css3 css-transitions carousel

Pi带this questionexcellent answer的东西,我需要做更多的工作。我也有类似的滚动需求,但有子div而不是list元素,重要的是div包含宽度相同但高度可变的图像。使用动画/滚动顶部时,我无法流畅滚动。

本质上,我想要这样的行为,例如codepen,但高度可变,例如this codepen(不起作用),因为子元素的高度不允许设置动画的scrollTop准确计算:

setInterval(function(){
 var first_height = $('#list').find('div:first').height(); $('#list').stop().animate({scrollTop:first_height},2650,'linear',function(){
    $(this).scrollTop(0).find('div:last').after($('div:first', this));
  });
}, 2700);

有人可以提供任何提示吗?

编辑:this pen based on the answer below几乎在那儿。我获得了“捕捉到网格”功能,而不是平滑滚动。

1 个答案:

答案 0 :(得分:0)

这是因为您在CSS中设置了固定高度,但是没有将填充边距包括在总计中您要设置scrollTop动画的div的高度

为了实现容器中每个元素的精确测量,我们需要使用 jQuery.css()获得元素的实际填充和边距。

  

注意

jQuery.css()函数不支持

CSS速记属性。因此,我们需要以传统方式(LMAO)定义所有内容。

必须使用 parseInt(),因为 jQuery 函数的结果将以字符/字符串的形式返回,从而将两个结果连接在一起而不是添加它们。

  

示例:parseInt($('#list')。find('div:first')。css('padding-top'))+ parseInt($('#list')。find('div:first ').css('padding-bottom'));

     

将导致 [10 + 10 = 20]

     

和$('#list')。find('div:first')。css('padding-top')+ $('#list')。find('div:first')。css(' padding-bottom');

     

将导致 ['10'+'10'='1010']

var interval = 1000;
setInterval(function() {
var first_height = $('#list').find('div:first').height();
var paddings = parseInt($('#list').find('div:first').css('padding-top')) + parseInt($('#list').find('div:first').css('padding-bottom'));
var margins = parseInt($('#list').find('div:first').css('margin-top')) + parseInt($('#list').find('div:first').css('margin-bottom'));
var animation = interval - paddings - margins;
  $('#list').stop().animate({
    scrollTop: first_height + paddings + margins
  }, animation, 'linear', function() {
    $(this).scrollTop(0).find('div:last').after($('div:first', this));
  });
}, interval);
* {
  box-sizing: border-box;
}

#list {
  overflow: hidden;
  width: 300px;
  height: 250px;
  background: red;
  padding: 10px;
}

#list div {
  display: block;
  padding: 10px 10px;
  margin-bottom: 10px;
  background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="list">
  <div style="height: 30px;">Item 1</div>
  <div style="height: 50px;">Item 2</div>
  <div style="height: 30px;">Item 3</div>
  <div style="height: 50px;">Item 4</div>
  <div style="height: 30px;">Item 5</div>
  <div style="height: 50px;">Item 6</div>
  <div style="height: 30px;">Item 7</div>
  <div style="height: 50px;">Item 8</div>
  <div style="height: 30px;">Item 9</div>
  <div style="height: 50px;">Item 10</div>
</div>

  

来源:jQuery API | .css()jQuery API | .animate()