如何在HTML滚动跑马灯中显示当前日期、时间及地理位置
解决方案:为滚动跑马灯添加实时日期、时间与地理位置信息
首先调整HTML结构,给每个信息项添加可识别的标识,方便后续用JS更新内容:
<div class="hwrap"> <div class="hmove"> <div class="hitem">The time is: <span id="current-time"></span></div> <div class="hitem">The date is: <span id="current-date"></span></div> <div class="hitem">The location is: <span id="current-location"></span></div> </div> </div>
然后修正CSS动画参数——你当前是3个滚动项,原代码里的-400%是对应4个项目的,需要改成-300%避免滚动错位:
.hwrap { overflow: hidden; /* 隐藏滚动条 */ background: #eee; } .hmove { display: flex; } .hitem { flex-shrink: 0; width: 100%; box-sizing: border-box; padding: 10px; text-align: center; } /* 动画:从右向左滚动 */ /* 3个项目对应-300%,增减项目时需同步修改该值 */ @keyframes tickerh { 0% {transform: translate3d(100%, 0, 0);} 100% {transform: translate3d(-300%, 0, 0);} } .hmove {animation: tickerh linear 15s infinite;} .hmove:hover {animation-play-state: paused;}
最后添加JavaScript代码,实现实时更新与地理位置获取:
// 更新时间和日期 function updateDateTime() { const now = new Date(); // 格式化12小时制带AM/PM的时间 const timeStr = now.toLocaleTimeString('en-US'); // 格式化完整日期(星期+月+日+年) const dateStr = now.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }); document.getElementById('current-time').textContent = timeStr; document.getElementById('current-date').textContent = dateStr; } // 获取地理位置 function getLocation() { if (!navigator.geolocation) { document.getElementById('current-location').textContent = "Geolocation is not supported by your browser"; return; } function success(position) { const lat = position.coords.latitude; const lon = position.coords.longitude; // 直接显示经纬度,若需要具体地名可结合地理编码服务(需自行处理跨域与API密钥) document.getElementById('current-location').textContent = `Latitude: ${lat.toFixed(4)}, Longitude: ${lon.toFixed(4)}`; } function error() { document.getElementById('current-location').textContent = "Unable to retrieve your location"; } navigator.geolocation.getCurrentPosition(success, error); } // 初始化执行 updateDateTime(); // 每秒刷新一次时间 setInterval(updateDateTime, 1000); // 获取地理位置 getLocation();
关键说明:
- 实时时间更新:通过
setInterval每秒调用一次更新函数,保证时间始终是最新状态;使用toLocale*String方法可以快速生成本地化的时间日期格式。 - 地理位置获取:利用浏览器原生的
navigator.geolocationAPI,用户授权后即可获取经纬度;如果需要显示具体城市名称,可自行对接第三方地理编码服务。 - 动画适配:滚动动画的最终位移值需要和项目数量匹配,n个项目对应
-n*100%,否则会出现滚动空白或内容重叠。
内容的提问来源于stack exchange,提问作者k011
相关产品推荐
相关产品推荐

