jquery图片滚动
jQuery 图片滚动实现方法
水平无缝滚动
通过设置容器宽度和动画效果实现水平滚动,适合轮播图或横向展示。
$(function() {
var $container = $('.scroll-container');
var $content = $('.scroll-content');
var itemWidth = $content.find('img').outerWidth(true);
function scroll() {
$content.animate({left: -itemWidth}, 500, function() {
$content.find('img:first').appendTo($content);
$content.css('left', 0);
});
}
var timer = setInterval(scroll, 2000);
$container.hover(function() {
clearInterval(timer);
}, function() {
timer = setInterval(scroll, 2000);
});
});
HTML结构示例:
<div class="scroll-container" style="width:600px;overflow:hidden">
<div class="scroll-content" style="width:2000px;position:relative">
<img src="1.jpg">
<img src="2.jpg">
<img src="3.jpg">
</div>
</div>
垂直淡入淡出滚动
通过改变透明度和位置实现垂直渐变效果,适合新闻列表或公告。
$(function() {
var $items = $('.vertical-scroll li');
var current = 0;
function nextItem() {
$items.eq(current).fadeOut(500);
current = (current + 1) % $items.length;
$items.eq(current).fadeIn(500);
}
setInterval(nextItem, 3000);
});
CSS建议:
.vertical-scroll {
position: relative;
height: 200px;
}
.vertical-scroll li {
position: absolute;
display: none;
}
使用插件实现
推荐使用Slick插件实现复杂滚动效果,支持响应式和多种参数配置。
安装:
npm install slick-carousel
基础调用:
$('.slider').slick({
dots: true,
infinite: true,
speed: 500,
slidesToShow: 3,
slidesToScroll: 1,
autoplay: true
});
触摸屏适配
添加touch事件处理实现移动端友好交互:

var startX, moveX;
$('.scroll-container').on('touchstart', function(e) {
startX = e.originalEvent.touches[0].pageX;
}).on('touchmove', function(e) {
moveX = e.originalEvent.touches[0].pageX;
}).on('touchend', function() {
if(startX - moveX > 50) {
// 向左滑动逻辑
} else if(moveX - startX > 50) {
// 向右滑动逻辑
}
});
性能优化建议
- 使用
will-change: transform提升动画性能 - 对图片进行预加载避免空白
- 合理设置间隔时间,通常3000-5000ms为宜
- 使用
requestAnimationFrame替代setInterval
function smoothScroll() {
// 动画逻辑
requestAnimationFrame(smoothScroll);
}
requestAnimationFrame(smoothScroll);
以上方法可根据实际需求组合使用,注意容器需要设置overflow: hidden,图片元素需要统一尺寸以确保滚动效果稳定。对于复杂场景建议优先考虑成熟插件方案。






