关于实现导航栏内滑板左右往返动画的技术咨询
问题解答与代码修改
你的两个疑问解答
元素样式该放CSS还是JS?
大部分静态样式(比如滑板的尺寸、背景、定位规则,导航栏的布局)都应该留在CSS里,JS只负责控制动态变化的属性(比如这里的left位置)。这样代码分工更清晰,后期维护样式也更方便,不用去JS里找样式代码。如何获取元素宽度?
可以用DOM元素的offsetWidth或者clientWidth属性:
offsetWidth:包含元素的内容、内边距、边框的总宽度clientWidth:只包含内容和内边距,不含边框和滚动条
这里导航栏的宽度用navBar.offsetWidth就足够了。
修改后的代码
JavaScript
const navBar = document.getElementById('nav-bar'); function moveSkateboard() { // 精准选中导航栏里的滑板div,避免选到页面其他div const skateboard = navBar.querySelector('div'); let position = 0; let direction = 1; let speed = 1; // 提前获取导航栏和滑板的宽度,避免每次move都重复计算 const navWidth = navBar.offsetWidth; const skateWidth = skateboard.offsetWidth; function move() { position += direction * speed; skateboard.style.left = position + 'px'; // 边界判断换成导航栏的宽度,确保滑板在导航栏内移动 if (position >= navWidth - skateWidth) { direction = -1; } else if (position <= 0) { direction = 1; } requestAnimationFrame(move); } requestAnimationFrame(move); } moveSkateboard();
CSS(保留原有代码即可)
header { width: 100%; display: flex; justify-content: space-around; align-items: center; box-shadow: 0 1px 4px rgba(0, 155, 68, 1); } img { width: 10%; } nav { position: relative; display: flex; justify-content: center; align-items: center; width: 40%; height: 6.125em; } nav a { font-size: 1.25rem; font-weight: 900; color:#009344; text-decoration: none; padding: 0 1.5em; } nav div { background: no-repeat center/70% url("../images/skateboard-navBar.png") ; width: 5.9375em; height: 100%; position: absolute; top: 1.5em; transition: .5s ease; }
HTML(保留原有代码即可)
<header> <img src="./images/btrLogoBlack.png" alt="BTR Logo"> <nav id="nav-bar"> <a href="index.html">Home</a> <a href="about.html">About</a> <a href="events.html">Events</a> <a href="donate.html">Donate</a> <a href="contact.html">Contact</a> <div></div> </nav> </header> <h1>Home Page</h1> <p>In the nav bar there is a skateboard moving left to right and back, but it is the length of the window. The javaScript has window.innerWidth because I could not figure out how to only make it the width of the nav. But I wanted to know if my thought process would work. Now unfortunately I am stuck.</p>
关键修改点
- 把滑板的选择器从
document.querySelector('div')改成navBar.querySelector('div'),避免误选页面其他div元素 - 用
navBar.offsetWidth替代window.innerWidth,获取导航栏的实际宽度 - 提前计算导航栏和滑板的宽度,避免每次动画帧都重复获取,提升性能
- 边界判断逻辑改为基于导航栏宽度,确保滑板在导航栏范围内往返移动
内容的提问来源于stack exchange,提问作者Karen Byrd
相关产品推荐
相关产品推荐

