JavaScript 作为前端开发的核心语言,为网页设计和开发提供了强大的功能支持。以下列举10个经典的 JavaScript 网页设计案例,每个案例都包含一个简洁的代码示例,帮助大家更好地理解 JavaScript 在网页设计中的实际应用。
动态图片轮播
案例简介:动态图片轮播适用于展示广告、产品图片等,能够自动播放并支持手动切换。
代码示例:
<div class="slider">
<img id="slide" src="image1.jpg" alt="Slide">
</div>
<button onclick="prevSlide()">Previous</button>
<button onclick="nextSlide()">Next</button>
<script>
let images = ["image1.jpg", "image2.jpg", "image3.jpg"];
let currentIndex = 0;
function showSlide(index) {
document.getElementById('slide').src = images[index];
}
function nextSlide() {
currentIndex = (currentIndex + 1) % images.length;
showSlide(currentIndex);
}
function prevSlide() {
currentIndex = (currentIndex - 1 + images.length) % images.length;
showSlide(currentIndex);
}
setInterval(nextSlide, 3000);
</script>
悬停下拉菜单
案例简介:下拉菜单用于多级导航,提升用户的浏览体验。
代码示例:
<nav>
<ul>
<li onmouseover="showMenu()" onmouseout="hideMenu()">Menu
<ul id="submenu" style="display: none;">
<li>Option 1</li>
<li>Option 2</li>
</ul>
</li>
</ul>
</nav>
<script>
function showMenu() {
document.getElementById('submenu').style.display = 'block';
}
function hideMenu() {
document.getElementById('submenu').style.display = 'none';
}
</script>
模态弹窗
案例简介:模态弹窗用于提示信息或用户登录。
代码示例:
<button onclick="openModal()">Open Modal</button>
<div id="modal" style="display: none;">
<div class="modal-content">
<span onclick="closeModal()">Close</span>
<p>This is a modal window!</p>
</div>
</div>
<script>
function openModal() {
document.getElementById('modal').style.display = 'block';
}
function closeModal() {
document.getElementById('modal').style.display = 'none';
}
</script>
表单验证
案例简介:表单验证用于检查用户输入的有效性。
代码示例:
<form onsubmit="return validateForm()">
<label>Email:</label>
<input type="text" id="email">
<span id="error" style="color: red;"></span>
<button type="submit">Submit</button>
</form>
<script>
function validateForm() {
const email = document.getElementById('email').value;
const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (!emailPattern.test(email)) {
document.getElementById('error').textContent = "Invalid email";
return false;
}
document.getElementById('error').textContent = "";
return true;
}
</script>
响应式导航栏
案例简介:响应式导航栏适用于移动设备和桌面设备的自动调整。
代码示例:
<div class="nav">
<button onclick="toggleNav()">☰ Menu</button>
<ul id="navList" style="display: none;">
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
<script>
function toggleNav() {
const navList = document.getElementById('navList');
if (navList.style.display === 'none') {
navList.style.display = 'block';
} else {
navList.style.display = 'none';
}
}
</script>
滚动到顶部按钮
案例简介:滚动到顶部按钮能够快速返回页面顶部。
代码示例:
<button id="topBtn" onclick="scrollToTop()" style="display: none;">Top</button>
<script>
window.onscroll = function() {
document.getElementById('topBtn').style.display = window.scrollY > 100 ? 'block' : 'none';
};
function scrollToTop() {
window.scrollTo({ top: 0, behavior: 'smooth' });
}
</script>
倒计时计时器
案例简介:倒计时用于活动、促销等场景。
代码示例:
<div id="countdown"></div>
<script>
const countdownDate = new Date("2025-01-01").getTime();
const countdownInterval = setInterval(() => {
const now = new Date().getTime();
const distance = countdownDate - now;
const days = Math.floor(distance / (1000 * 60 * 60 * 24));
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("countdown").innerHTML = `${days}d ${hours}h ${minutes}m ${seconds}s`;
if (distance < 0) {
clearInterval(countdownInterval);
document.getElementById("countdown").innerHTML = "EXPIRED";
}
}, 1000);
</script>
图片懒加载
案例简介:图片懒加载用于提高网页加载性能。
代码示例:
<img data-src="image.jpg" class="lazy-load" width="200" height="200">
<script>
document.addEventListener("DOMContentLoaded", () => {
const lazyImages = document.querySelectorAll("img.lazy-load");
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
});
lazyImages.forEach(img => observer.observe(img));
});
</script>
图片放大镜效果
案例简介:放大镜效果用于细节展示。
代码示例:
<img id="image" src="image.jpg" width="300" height="200" onmousemove="zoom(event)" style="position:relative;">
<script>
function zoom(event) {
const image = document.getElementById('image');
const zoomLevel = 2;
const rect = image.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
image.style.transformOrigin = `${x}px ${y}px`;
image.style.transform = `scale(${zoomLevel})`;
}
</script>
数字滚动动画
案例简介:数字滚动用于展示统计数据,如访问量、销售量等。
代码示例:
<div id="counter" data-target="5000">0</div>
<script>
const counter = document.getElementById('counter');
const target = +counter.getAttribute('data-target');
let count = 0;
const updateCount = () => {
const increment = target / 200;
count += increment;
counter.innerText = Math.floor(count);
if (count < target) {
requestAnimationFrame(updateCount);
}
};
updateCount();
</script>
以上10个经典 JavaScript 案例涵盖了动态效果、交互功能和性能优化等不同方面。这些案例不仅能够提升网页的用户体验,还能帮助开发者掌握 JavaScript 的基本应用。希望这些代码示例能够为大家提供灵感,让网页设计更加出色。