JavaScript网页设计8个经典案例
以下是8个经典的JavaScript网页设计案例,这些案例展示了JavaScript在前端开发中的强大功能支持。每个案例都配有简洁的代码示例,以帮助大家更好地理解其在实际应用中的作用。
1. 图片轮播
功能描述:图片轮播组件,点击按钮查看下一张或上一张图片,图片会进行平滑的切换。
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片轮播</title>
<style>
.carousel {
position: relative;
width: 600px;
height: 400px;
overflow: hidden;
}
.carousel-images {
display: flex;
transition: transform 0.5s ease-in-out;
}
.carousel-images img {
width: 600px;
height: 400px;
min-width: 600px;
}
button {
position: absolute;
top: 50%;
transform: translateY(-50%);
background-color: rgba(0, 0, 0, 0.5);
color: white;
border: none;
padding: 10px;
cursor: pointer;
}
#prevBtn {
left: 10px;
}
#nextBtn {
right: 10px;
}
</style>
</head>
<body>
<div class="carousel">
<div class="carousel-images">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>
<button id="prevBtn">Previous</button>
<button id="nextBtn">Next</button>
</div>
<script>
let currentIndex = 0;
const images = document.querySelectorAll('.carousel-images img');
const totalImages = images.length;
const imageContainer = document.querySelector('.carousel-images');
const nextBtn = document.getElementById('nextBtn');
const prevBtn = document.getElementById('prevBtn');
function updateCarousel() {
imageContainer.style.transform = `translateX(${-currentIndex * 600}px)`;
}
nextBtn.addEventListener('click', () => {
currentIndex = (currentIndex + 1) % totalImages;
updateCarousel();
});
prevBtn.addEventListener('click', () => {
currentIndex = (currentIndex - 1 + totalImages) % totalImages;
updateCarousel();
});
</script>
</body>
</html>
2. 简单的表单验证
功能描述:表单验证功能,用户在输入数据后点击提交按钮,系统检查所填内容是否符合预设的数据格式要求。
代码示例:
<!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>
.error {
color: red;
}
</style>
</head>
<body>
<form id="myForm">
<label for="username">用户名:</label>
<input type="text" id="username" name="username">
<p class="error" id="errorNameMsg"></p><br>
<label for="email">邮箱:</label>
<input type="text" id="email" name="email">
<p class="error" id="errorEmailMsg"></p><br>
<button type="submit">提交</button>
</form>
<script>
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault(); // 阻止表单提交
// 获取表单元素
const username = document.getElementById('username').value;
const email = document.getElementById('email').value;
// 验证用户名(非空)
if (username.trim() === '') {
document.getElementById('errorNameMsg').innerHTML = "用户名不能为空";
return
}
// 验证电子邮件(简单的正则表达式检查)
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
document.getElementById('errorEmailMsg').innerHTML = "非有效的邮箱地址";
return
}
// 如果所有验证通过,可以提交表单或执行其他操作
alert('Form submitted successfully!');
// 这里可以添加表单提交逻辑,例如使用 AJAX 提交表单数据
});
</script>
</body>
</html>
3. 时间显示
功能描述:动态时间显示功能,页面上展示当前的年、月、日、时、分、秒信息,并且每秒自动更新一次。
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>时间显示</title>
</head>
<body>
<div id="clockBox"></div>
<script>
const clockDom = document.getElementById("clockBox");
function clockTime() {
const now = new Date();
clockDom.innerText= now.toLocaleString();
}
setInterval(clockTime, 1000);
clockTime();
</script>
</body>
</html>
4. 倒计时
功能描述:倒计时功能,设置特定的时间节点,以便对该时间进行倒计时,常用于节日、活动等场景。
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>倒计时</title>
</head>
<body>
<div id="countdown"></div>
<script>
// 设置目标日期
const targetDate = new Date('2025-03-01');
// 获取显示倒计时的元素
const countdownElement = document.getElementById('countdown');
// 定义一个函数来更新倒计时显示
function updateCountdown() {
// 获取当前时间
const now = new Date();
// 计算剩余的时间差(以毫秒为单位)
const timeDifference = targetDate - now;
// 如果时间差小于等于0,表示已经过了目标日期
if (timeDifference <= 0) {
clearInterval(intervalId);
countdownElement.innerText= "已经过去了!";
return;
}
// 将时间差转换为天、小时、分钟和秒
const days = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
const hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((timeDifference % (1000 * 60)) / 1000);
// 格式化时间,使其始终显示两位数字
const formattedDays = days < 10 ? '0' + days : days;
const formattedHours = hours < 10 ? '0' + hours : hours;
const formattedMinutes = minutes < 10 ? '0' + minutes : minutes;
const formattedSeconds = seconds < 10 ? '0' + seconds : seconds;
// 更新页面上的倒计时显示
countdownElement.innerText= `距离***还有 ${formattedDays} 天 ${formattedHours} 小时 ${formattedMinutes} 分钟 ${formattedSeconds} 秒`;
}
// 每秒调用一次updateCountdown函数
const intervalId = setInterval(updateCountdown, 1000);
// 初始化倒计时显示
updateCountdown();
</script>
</body>
</html>
5. 悬停下拉菜单
功能描述:下拉菜单,鼠标悬停在上级菜单项上时,与之相关的下级菜单会平滑展开,常用于多级导航,提升用户的浏览体验。
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dropdown Menu</title>
<style>
*{
margin: 0;
padding: 0;
list-style: none;
text-decoration: none;
}
.menu {
display: flex;
}
.menu-item {
position: relative;
}
.menu-item a {
display: block;
color: rgb(41, 41, 41);
padding: 10px 20px;
}
.dropdown {
display: none;
position: absolute;
top: 100%;
left: 0;
}
.dropdown li a {
color: rgb(29, 29, 29);
display: block;
min-width: 120px;
}
</style>
</head>
<body>
<nav class="navbar">
<ul class="menu">
<li class="menu-item" onmouseenter="mouseEnter()" onmouseleave="mouseLeave()">
<a href="#">Menu 1</a>
<ul class="dropdown">
<li><a href="#">Submenu 1-1</a></li>
<li><a href="#">Submenu 1-2</a></li>
<li><a href="#">Submenu 1-3</a></li>
</ul>
</li>
</ul>
</nav>
<script>
const dropdown = document.querySelector('.dropdown');
function mouseEnter(){
dropdown.style.display = 'block';
}
function mouseLeave(){
dropdown.style.display = 'none';
}
</script>
</body>
</html>
6. 模态弹窗
功能描述:模态弹窗是一种常见的用户界面元素,它主要用于提示信息或引导用户进行登录操作。
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>模态弹窗</title>
<style>
#modalDialog{
display: none;
position: fixed;
width: 100%;
height: 100%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(0,0,0,0.6);
padding: 20px;
border: 2px solid black;
}
</style>
</head>
<body>
<button onclick="openModal()">打开弹窗页面</button>
<div id="modalDialog">
<div class="modal-content">
<p>这是一个弹窗页面!</p>
<span onclick="closeModal()">关闭</span>
</div>
</div>
<script>
const modalDom = document.getElementById('modalDialog')
function openModal() {
modalDom.style.display = 'block';
}
function closeModal() {
modalDom.style.display = 'none';
}
</script>
</body>
</html>
7. 滚动到顶部功能
功能描述:滚动到顶部按钮能够快速返回页面顶部。
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>滚动到顶部功能</title>
<style>
#container{
height: 900px;
overflow: auto;
}
#content{
height: 1500px;
}
#topBtn{
position: fixed;
right: 40px;
bottom: 100px;
display: none;
}
</style>
</head>
<body>
<div id="container" onscroll="myScroll(this)">
<div id="content"></div>
</div>
<button id="topBtn" onclick="scrollToTop()">Top</button>
<script>
function myScroll(e) {
document.getElementById('topBtn').style.display = e.scrollTop > 100 ? 'block' : 'none';
};
function scrollToTop() {
document.getElementById("container").scrollTo({ top: 0, behavior: 'smooth' });
}
</script>
</body>
</html>
8. 计数器功能
功能描述:计数器功能,用户可以点击按钮来增加、减少或重置计数值。
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>计数器</title>
</head>
<body>
<div>
<div id="count">0</div>
<button onclick="increase()">增加</button>
<button onclick="reduce()">减少</button>
<button onclick="reset()">重置</button>
</div>
<script>
let count = 0;
const countDom = document.getElementById('count');
function increase() {
count++;
countDom.innerText= count;
}
function reduce() {
count--;
countDom.innerText = count;
}
function reset() {
count = 0;
countDom.innerText = count;
}
</script>
</body>
</html>
总结
以上这些JavaScript案例涵盖动态效果、交互功能等等,便于提升用户体验,为开发者提供学习资源。同时在实际项目中扩展和优化,能助力网页设计更上一层楼。