如何基于jQuery+PHP实现无marquee标签的无限循环水平滚动跑马灯
解决方案:无限循环水平滚动新闻跑马灯(jQuery + PHP)
一、为什么放弃<marquee>?
原生<marquee>标签的循环逻辑有缺陷,滚动到末尾会出现明显停顿和重置,无法实现真正的无缝无限滚动。我们用jQuery结合CSS动画来解决这个问题。
二、实现步骤
1. PHP接口:获取并返回JSON数据
创建news-api.php文件,负责拉取外部JSON数据并返回前端:
<?php // 替换为你的外部JSON数据源地址 $externalJsonUrl = "https://your-external-json-url.com/news.json"; // 获取外部数据(若服务器禁用file_get_contents,可改用cURL) $jsonContent = file_get_contents($externalJsonUrl); $newsData = json_decode($jsonContent, true); // 截取前15条数据(和你原有逻辑一致) $targetNews = array_slice($newsData, 0, 15); // 返回JSON格式响应 header('Content-Type: application/json'); echo json_encode($targetNews); ?>
2. HTML结构
不用<marquee>,通过双列表复制实现无缝衔接:
<div class="news-ticker"> <div class="ticker-container"> <ul class="ticker-items" id="mainTicker"> <!-- 动态填充新闻内容 --> </ul> <ul class="ticker-items" id="cloneTicker"> <!-- 复制主列表内容,用于无缝滚动 --> </ul> </div> </div>
3. CSS样式
用CSS动画控制滚动逻辑,设置基础布局:
.news-ticker { width: 100%; overflow: hidden; background-color: #f8f8f8; padding: 6px 0; } .ticker-container { display: flex; white-space: nowrap; } .ticker-items { display: flex; list-style: none; margin: 0; padding: 0; animation: scroll 25s linear infinite; } .ticker-items li { padding: 0 22px; border-right: 1px solid #ddd; white-space: nowrap; line-height: 1.5; } /* 克隆列表和主列表动画同步 */ #cloneTicker { animation: scroll 25s linear infinite; } @keyframes scroll { 0% { transform: translateX(0); } 100% { transform: translateX(-100%); } } /* 鼠标悬停暂停滚动 */ .news-ticker:hover .ticker-items { animation-play-state: paused; }
4. jQuery逻辑:Ajax拉取数据+填充列表
$(document).ready(function() { // 从PHP接口获取新闻数据 $.ajax({ url: 'news-api.php', type: 'GET', dataType: 'json', success: function(newsList) { let itemHtml = ''; // 生成新闻列表HTML $.each(newsList, function(index, news) { itemHtml += `<li>${news.text}</li>`; }); // 填充主列表和克隆列表 $('#mainTicker').html(itemHtml); $('#cloneTicker').html(itemHtml); // 可选:根据内容长度动态调整滚动速度 const listWidth = $('#mainTicker').outerWidth(); const scrollDuration = listWidth / 45; // 45px/秒的滚动速度,可自行调整 $('.ticker-items').css('animation-duration', scrollDuration + 's'); }, error: function(xhr, status, err) { console.error('新闻加载失败:', err); $('#mainTicker').html('<li>新闻加载失败,请稍后重试</li>'); } }); });
三、核心原理
- 通过Ajax动态获取数据,避免页面初始化时直接渲染,支持后续数据更新。
- 复制一份新闻列表,让两个列表并排滚动:当第一个列表完全滚出视野时,第二个列表刚好衔接上来,视觉上实现无缝无限循环。
- CSS动画比
<marquee>更灵活,支持暂停、速度调整等交互优化。
四、注意事项
- 若服务器禁用
file_get_contents,可改用cURL实现外部数据拉取,稳定性更强。 - 调整CSS的
animation-duration或JS中的scrollDuration可控制滚动速度,数值越小速度越快。 - 如需添加点击跳转,只需在
<li>标签内嵌套<a>链接即可。
内容的提问来源于stack exchange,提问作者KR Vineeth
相关产品推荐
相关产品推荐

