当前在点击 next 和 prev 时,列表的高度正在调整。我不想增加和减少高度,而是想用一组新内容替换当前内容。
期望:
- 如果我点击下一个/上一个,当前可见列表应该替换为带有一些幻灯片动画的新元素集。
- 此外,每次我需要显示 3 个元素时,在当前情况下,一旦下一个/上一个迭代完成,只有 2 个元素可见。
这是我尝试过的:
JS:
$(document).ready(function () {
size_li = $("#list li").size();
x=3;
$('#list li:lt('+x+')').show();
$('#next').click(function () {
x= (x+3 <= size_li) ? x+3 : size_li;
$('#list li:lt('+x+')').show();
$('#prev').show();
if(x == size_li){
$('#next').hide();
}
});
$('#prev').click(function () {
x=(x-3<0) ? 3 : x-3;
$('#list li').not(':lt('+x+')').hide();
$('#next').show();
if(x < 3){
$('#prev').hide();
}
});
});
JS fiddle :
最佳答案
我处理这个问题的方式有点不同。这是 fiddle .
我的解决方案的要点是我使用了 jQuery 的 animate
函数来实现平滑的滚动效果:
$('ul').animate({
scrollTop: $('ul').scrollTop() + height_to_show
}, 500);
但是,有一个问题是 ul
和 li
元素需要有固定高度。这些高度是根据您设置的以下变量在内部计算得出的:
/**
* Total number of elements in the list
* @type {Number}
*/
var num_of_elems = 8;
/**
* Static height of each element (in pixels)
* @type {Number}
*/
var height_of_elem = 25;
/**
* Number of elements you want to show in the page
* @type {Number}
*/
var num_of_elems_to_show = 3;
/**
* The visible height of the ul
* @type {Number}
*/
var height_to_show = 0; //calculated internally
更新
这是更新的 fiddle .
我添加了根据当前显示的页面隐藏或显示 prev
和 next
按钮的功能。
/**
* Show or hide the prev and next button depending on the current_page
*/
var show_hide_buttons = function() {
if (current_page === Math.ceil(num_of_elems / num_of_elems_to_show) - 1) {
$('#next').hide();
} else {
$('#next').show();
}
if (current_page === 0) {
$('#prev').hide();
} else {
$('#prev').show();
}
};
关于javascript - 如何为自定义垂直 slider 设置动画 Jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37234852/