jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。新闻自动向上滚动是一种常见的网页效果,通常用于展示最新消息或公告。
新闻自动向上滚动主要分为两种类型:
jquery.marquee
或 jquery.news-ticker
。新闻自动向上滚动常用于以下场景:
以下是一个使用 jQuery 实现新闻自动向上滚动的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>News Scrolling</title>
<style>
#news-container {
width: 100%;
height: 50px;
overflow: hidden;
position: relative;
}
#news-item {
position: absolute;
white-space: nowrap;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="news-container">
<div id="news-item">This is the latest news item that will scroll up automatically.</div>
</div>
<script>
$(document).ready(function() {
var $newsItem = $('#news-item');
var newsHeight = $newsItem.height();
var containerHeight = $('#news-container').height();
var scrollSpeed = 2; // pixels per second
function scrollNews() {
$newsItem.animate({ top: -newsHeight }, 1000 / scrollSpeed, function() {
$newsItem.css('top', containerHeight);
scrollNews();
});
}
scrollNews();
});
</script>
</body>
</html>
scrollSpeed
变量的值,增加或减少滚动速度。position
和 overflow
属性。#news-container
的高度设置正确,并且 #news-item
的内容不会超出容器高度。通过以上方法,可以实现一个简单且流畅的新闻自动向上滚动效果。
领取专属 10元无门槛券
手把手带您无忧上云