以下是6个基于JavaScript的网页设计案例,每个案例都涵盖不同的JavaScript应用场景,适用于初学者和中级开发者学习和实践。
1. 动态时钟
概述:
通过JavaScript实现一个动态时钟,页面上显示当前时间,并且每秒更新一次。
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Clock</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
font-family: Arial, sans-serif;
}
#clock {
font-size: 48px;
font-weight: bold;
}
</style>
</head>
<body>
<div id="clock"></div>
<script>
function updateClock() {
const clockElement = document.getElementById('clock');
const now = new Date();
clockElement.textContent = now.toLocaleTimeString();
}
setInterval(updateClock, 1000);
updateClock(); // Initial call to set time right away
</script>
</body>
</html>
说明:
- 通过
setInterval
每隔 1 秒更新一次当前时间。 - 使用
Date
对象来获取系统的当前时间,并通过toLocaleTimeString
格式化显示。
2. 图片轮播
概述:
通过JavaScript实现一个简单的图片轮播组件,用户可以点击按钮查看下一张或上一张图片。
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Carousel</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
font-family: Arial, sans-serif;
}
img {
width: 500px;
height: 300px;
object-fit: cover;
display: none;
}
#carousel img.active {
display: block;
}
button {
padding: 10px;
margin: 5px;
}
</style>
</head>
<body>
<div id="carousel">
<img src="image1.jpg" class="active">
<img src="image2.jpg">
<img src="image3.jpg">
</div>
<button onclick="previousImage()">Previous</button>
<button onclick="nextImage()">Next</button>
<script>
let currentImageIndex = 0;
const images = document.querySelectorAll('#carousel img');
function showImage(index) {
images.forEach((img, i) => {
img.classList.toggle('active', i === index);
});
}
function nextImage() {
currentImageIndex = (currentImageIndex + 1) % images.length;
showImage(currentImageIndex);
}
function previousImage() {
currentImageIndex = (currentImageIndex - 1 + images.length) % images.length;
showImage(currentImageIndex);
}
</script>
</body>
</html>
说明:
- 利用
querySelectorAll
获取所有图片并通过classList
切换展示图片。 nextImage
和previousImage
函数用于控制图片的循环显示。
3. 计数器应用
概述:
实现一个计数器,用户可以点击按钮来增加、减少或重置计数值。
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Counter App</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
font-family: Arial, sans-serif;
}
#counter {
font-size: 48px;
margin-bottom: 20px;
}
button {
padding: 10px;
margin: 5px;
}
</style>
</head>
<body>
<div>
<div id="counter">0</div>
<button onclick="increment()">Increase</button>
<button onclick="decrement()">Decrease</button>
<button onclick="reset()">Reset</button>
</div>
<script>
let count = 0;
const counterElement = document.getElementById('counter');
function increment() {
count++;
counterElement.textContent = count;
}
function decrement() {
count--;
counterElement.textContent = count;
}
function reset() {
count = 0;
counterElement.textContent = count;
}
</script>
</body>
</html>
说明:
- 计数器通过 JavaScript 操作 DOM 来更新显示的值。
- 三个按钮分别用于增加、减少和重置计数值。
4. 简单的表单验证
概述:
实现一个简单的表单验证,用户输入数据后点击提交按钮,验证数据格式是否符合要求。
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
<style>
form {
display: flex;
flex-direction: column;
width: 300px;
margin: 100px auto;
}
input, button {
margin: 10px 0;
padding: 10px;
}
.error {
color: red;
display: none;
}
</style>
</head>
<body>
<form id="myForm">
<input type="text" id="name" placeholder="Enter your name" required>
<input type="email" id="email" placeholder="Enter your email" required>
<span id="errorMessage" class="error">Please fill all fields correctly.</span>
<button type="submit">Submit</button>
</form>
<script>
const form = document.getElementById('myForm');
const nameInput = document.getElementById('name');
const emailInput = document.getElementById('email');
const errorMessage = document.getElementById('errorMessage');
form.addEventListener('submit', function (event) {
if (!nameInput.value || !emailInput.value || !emailInput.validity.valid) {
errorMessage.style.display = 'block';
event.preventDefault();
} else {
errorMessage.style.display = 'none';
}
});
</script>
</body>
</html>
说明:
- 表单提交时,通过 JavaScript 检查输入是否为空以及 Email 格式是否有效。
- 如果有错误,显示错误信息并阻止表单提交。
5. 模态框(Modal)弹窗
概述:
实现一个模态框弹窗,用户点击按钮时弹出模态框,点击关闭按钮时隐藏模态框。
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Modal Popup</title>
<style>
body {
font-family: Arial, sans-serif;
}
#modal {
display: none;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: white;
padding: 20px;
border: 2px solid black;
}
#modal.active {
display: block;
}
#overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
}
#overlay.active {
display: block;
}
button {
margin: 10px;
}
</style>
</head>
<body>
<button onclick="openModal()">Open Modal</button>
<div id="overlay"></div>
<div id="modal">
<p>This is a modal popup!</p>
<button onclick="closeModal()">Close</button>
</div>
<script>
const modal = document.getElementById('modal');
const overlay = document.getElementById('overlay');
function openModal() {
modal.classList.add('active');
overlay.classList.add('active');
}
function closeModal() {
modal.classList.remove('active');
overlay.classList.remove('active');
}
</script>
</body>
</html>
说明:
- 模态框和覆盖层通过
classList
的add
和remove
方法进行显示和隐藏。 - 模态框在屏幕中央显示,点击按钮可打开和关闭模态框。
6. 滚动侦听器(Scroll Listener)
概述:
实现一个滚动侦听器,当用户滚动页面时,显示或隐藏一个返回顶部的按钮。
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Scroll Listener</title>
<style>
body {
height: 2000px;
font-family: Arial, sans-serif;
}
#scrollTopButton {
position: fixed;
bottom: 30px;
right: 30px;
padding: 10px 20px;
background-color: #007BFF;
color: white;
border: none;
border-radius: 5px;
display: none;
}
</style>
</head>
<body>
<button id="scrollTopButton" onclick="scrollToTop()">Scroll to Top</button>
<script>
const scrollTopButton = document.getElementById('scrollTopButton');
window.onscroll = function () {
if (window.scrollY > 300) {
scrollTopButton.style.display = 'block';
} else {
scrollTopButton.style.display = 'none';
}
};
function scrollToTop() {
window.scrollTo({ top: 0, behavior: 'smooth' });
}
</script>
</body>
</html>
说明:
onscroll
事件监听器用于监控用户的滚动,当滚动超过 300px 时显示返回顶部按钮。scrollTo
方法使页面平滑地返回顶部。
结语
这些案例展示了如何在网页设计中利用JavaScript完成常见的功能,从简单的交互效果到用户体验的提升。每个案例都可以在实际项目中进行扩展和定制。