jQuery无缝滚动是一种网页效果,通过动态地复制和移动元素,使得滚动看起来像是连续不断的。这种效果常用于新闻滚动、图片轮播等场景。
以下是一个简单的jQuery无缝滚动代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery 无缝滚动</title>
<style>
#scroll-container {
width: 300px;
height: 100px;
overflow: hidden;
border: 1px solid #ccc;
}
#scroll-content {
white-space: nowrap;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="scroll-container">
<div id="scroll-content">
<span>新闻1</span>
<span>新闻2</span>
<span>新闻3</span>
<span>新闻4</span>
<span>新闻5</span>
</div>
</div>
<script>
$(document).ready(function() {
var $scrollContent = $('#scroll-content');
var $first = $scrollContent.find('span:first');
var itemWidth = $first.outerWidth(true);
function scroll() {
$scrollContent.animate({
marginLeft: -itemWidth
}, 1000, function() {
$scrollContent.css({ marginLeft: 0 }).append($first.clone());
$first.remove();
$first = $scrollContent.find('span:first');
});
}
setInterval(scroll, 3000);
});
</script>
</body>
</html>
requestAnimationFrame
代替setInterval
。通过以上示例代码和解决方法,你可以实现一个简单的jQuery无缝滚动效果,并解决常见的滚动问题。
领取专属 10元无门槛券
手把手带您无忧上云