JavaScript 是一种广泛使用的编程语言,用于实现网页上的交互效果。下面是一些常见的 JavaScript 网页设计案例及其代码示例。
1. 动态按钮效果
HTML
动态按钮效果
JavaScript (script.js)
document.getElementById('myButton').addEventListener('click', function() {
alert('按钮被点击了!');
});
2. 切换文本
HTML
切换文本
初始文本
JavaScript (script.js)
document.getElementById('toggleButton').addEventListener('click', function() {
const textElement = document.getElementById('toggleText');
if (textElement.textContent === '初始文本') {
textElement.textContent = '新的文本';
} else {
textElement.textContent = '初始文本';
}
});
3. 图片轮播
HTML
图片轮播
JavaScript (script.js)
const images = document.querySelectorAll('.carousel img');
let index = 0;
function showImage() {
for (let i = 0; i < images.length; i++) {
images[i].style.display = 'none';
}
images[index].style.display = 'block';
index = (index + 1) % images.length;
}
setInterval(showImage, 2000); // 每两秒切换一次图片
4. 表单验证
HTML
表单验证
JavaScript (script.js)
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault();
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
let hasErrors = false;
if (username.trim() === '') {
document.getElementById('usernameError').textContent = '用户名不能为空';
hasErrors = true;
} else {
document.getElementById('usernameError').textContent = '';
}
if (password.trim() === '') {
document.getElementById('passwordError').textContent = '密码不能为空';
hasErrors = true;
} else {
document.getElementById('passwordError').textContent = '';
}
if (!hasErrors) {
alert('表单提交成功!');
}
});
5. AJAX 数据请求
HTML
AJAX 数据请求
JavaScript (script.js)
document.getElementById('fetchData').addEventListener('click', function() {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(data => {
const dataContainer = document.getElementById('dataContainer');
dataContainer.innerHTML = `${JSON.stringify(data, null, 2)}
`;
})
.catch(error => {
console.error('Error fetching data:', error);
});
});
6. 动态表格生成
HTML
动态表格生成
JavaScript (script.js)
document.getElementById('generateTable').addEventListener('click', function() {
const table = document.createElement('table');
const thead = document.createElement('thead');
const tbody = document.createElement('tbody');
// 创建表头
const headerRow = document.createElement('tr');
const headers = ['姓名', '年龄', '城市'];
headers.forEach(headerText => {
const th = document.createElement('th');
th.textContent = headerText;
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
table.appendChild(thead);
// 创建表格数据
const data = [
{ name: '张三', age: 25, city: '北京' },
{ name: '李四', age: 30, city: '上海' },
{ name: '王五', age: 28, city: '广州' }
];
data.forEach(item => {
const row = document.createElement('tr');
Object.values(item).forEach(value => {
const cell = document.createElement('td');
cell.textContent = value;
row.appendChild(cell);
});
tbody.appendChild(row);
});
table.appendChild(tbody);
// 添加到页面
document.body.appendChild(table);
});
7. 拖拽排序列表
HTML
拖拽排序列表
- 项目 1
- 项目 2
- 项目 3
- 项目 4
JavaScript (script.js)
const draggableList = document.getElementById('draggableList');
// 设置拖拽事件
draggableList.addEventListener('dragstart', handleDragStart);
draggableList.addEventListener('dragover', handleDragOver);
draggableList.addEventListener('drop', handleDrop);
function handleDragStart(event) {
event.dataTransfer.setData('text/plain', event.target.id);
}
function handleDragOver(event) {
event.preventDefault();
}
function handleDrop(event) {
event.preventDefault();
const draggedItem = document.getElementById(event.dataTransfer.getData('text/plain'));
const targetItem = event.target.closest('li');
if (targetItem && draggedItem !== targetItem) {
if (event.clientY < targetItem.offsetTop + targetItem.offsetHeight / 2) {
targetItem.parentNode.insertBefore(draggedItem, targetItem);
} else {
targetItem.parentNode.insertBefore(draggedItem, targetItem.nextSibling);
}
}
}
// 初始化元素 ID
const items = document.querySelectorAll('#draggableList li');
items.forEach((item, index) => {
item.id = `item-${index}`;
item.draggable = true;
});
8. 响应式导航栏
HTML
响应式导航栏
JavaScript (script.js)
function toggleMenu() {
const navbar = document.getElementById('myNavbar');
if (navbar.className === 'navbar') {
navbar.className += ' responsive';
} else {
navbar.className = 'navbar';
}
}
9. 实时搜索过滤
HTML
实时搜索过滤
- 项目 1
- 项目 2
- 项目 3
- 项目 4
- 项目 5
JavaScript (script.js)
document.getElementById('searchInput').addEventListener('input', function() {
const searchTerm = this.value.toLowerCase();
const results = document.getElementById('searchResults');
const items = results.getElementsByTagName('li');
for (let i = 0; i < items.length; i++) {
const itemText = items[i].textContent.toLowerCase();
if (itemText.includes(searchTerm)) {
items[i].style.display = 'block';
} else {
items[i].style.display = 'none';
}
}
});