搭便车 this question和 excellent answer我有一些需要更多工作的东西。我有类似的滚动需求,但有子 div 而不是列表元素,重要的是 div 包含宽度相同但高度可变的图像。使用 animate/scrolltop 我无法平滑滚动。
本质上,我想要这样的行为 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 差不多了.我获得了“对齐网格”功能,而不是平滑滚动。
最佳答案
这是因为您在 CSS 中设置了固定高度,但没有将paddings 和margins 测量值计入您的总高度要设置 scrollTop 动画的 div 的 高度。
为了实现对容器中每个元素的精确测量,我们需要使用jQuery.css()获取元素的实际padding和margin。
TAKE NOTE
jQuery.css() 函数不支持 CSS 速记属性。因此,我们需要以传统方式 (LMAO) 定义所有内容。
使用 parseInt() 是必要的,因为 jQuery 函数的结果以 characters/string 的形式返回,从而连接两个结果而不是添加它们。
Example: parseInt($('#list').find('div:first').css('padding-top')) + parseInt($('#list').find('div:first').css('padding-bottom'));
will result in [10 + 10 = 20]
and $('#list').find('div:first').css('padding-top') + $('#list').find('div:first').css('padding-bottom');
will result in ['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 - 具有可变宽度子元素的CSS3/无限垂直滚动轮播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55051291/