CSS样式:美化导航器
为了让界面更具可读性和美观性,我们可以添加一些基本的CSS样式。
body {
margin: 0;
font-family: sans-serif;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh; /* 确保body占据视口完整高度 */
background-color: #f4f4f4;
}
.btn, .text {
position: absolute; /* 绝对定位,方便居中 */
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* 使用transform实现精确居中 */
}
.btn {
display: flex; /* 使用Flexbox布局按钮 */
gap: 120px; /* 按钮之间的间距 */
}
.lef, .rig {
font-size: 70px;
font-weight: 700;
background: none; /* 无背景 */
border: none; /* 无边框 */
cursor: pointer; /* 鼠标悬停时显示手型指针 */
color: #333;
transition: color 0.2s ease-in-out; /* 平滑过渡效果 */
}
.lef:hover, .rig:hover {
color: #007bff; /* 悬停时改变颜色 */
}
.text {
width: auto; /* 宽度自适应内容 */
height: 50px;
font-size: 30px;
background-color: #faebd7; /* 浅米色背景 */
display: grid; /* 使用Grid布局实现文本居中 */
place-items: center; /* 在Grid容器中居中内容 */
padding: .2em .8em; /* 文本内边距 */
border-radius: 8px; /* 圆角边框 */
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
min-width: 150px; /* 最小宽度 */
text-align: center; /* 文本居中 */
}这里我们使用 position: absolute 和 transform: translate(-50%, -50%) 将按钮容器和文本显示区域精确地居中于页面。Flexbox用于按钮的排列,而Grid则用于文本内容的垂直和水平居中。
JavaScript逻辑:实现前后导航
最后是核心的JavaScript部分,它负责处理所有的交互逻辑。
const fruits = ['apple', 'mango', 'banana', 'orange']; // 定义一个水果数组
// 获取DOM元素
const leftButton = document.querySelector('.lef');
const rightButton = document.querySelector('.rig');
const displayText = document.querySelector('.text');
// 初始化:在页面加载时显示数组的第一个元素
displayText.textContent = fruits[0];
// 定义一个变量来跟踪当前显示的数组元素的索引
let currentIndex = 0;
// 为左右按钮添加点击事件监听器
leftButton.addEventListener('click', handleLeftClick);
rightButton.addEventListener('click', handleRightClick);
/**
* 处理“上一项”按钮点击事件的函数。
* 当点击时,如果当前索引不是数组的第一个元素,则递减索引并更新显示。
*/
function handleLeftClick() {
if (currentIndex > 0) { // 检查是否已到达数组的起始位置
currentIndex--; // 递减索引
displayText.textContent = fruits[currentIndex]; // 更新显示内容
}
}
/**
* 处理“下一项”按钮点击事件的函数。
* 当点击时,如果当前索引不是数组的最后一个元素,则递增索引并更新显示。
*/
function handleRightClick() {
if (currentIndex < fruits.length - 1) { // 检查是否已到达数组的末尾位置
currentIndex++; // 递增索引
displayText.textContent = fruits[currentIndex]; // 更新显示内容
}
}代码解析:
- fruits 数组: 存储我们要导航的数据。
- DOM元素获取: 使用 document.querySelector 获取到左右按钮和显示文本的DOM元素,方便后续操作。
- **初始化显示:


