在网页开发中,JavaScript 不仅是实现交互功能的核心语言,更是提升用户体验的重要工具。为了帮助开发者更高效地掌握各种实用效果,本文整理了 420 个 JavaScript 特效代码示例,涵盖动画、表单验证、页面动态效果、数据处理等多个方面,适合初学者和进阶者参考使用。
一、基础特效类
1. 鼠标悬停变色
```javascript
document.getElementById("myButton").onmouseover = function() {
this.style.backgroundColor = "blue";
};
```
2. 点击按钮弹窗提示
```javascript
function showAlert() {
alert("欢迎访问!");
}
```
3. 文本输入框自动填充
```javascript
document.getElementById("username").value = "请输入用户名";
```
4. 页面加载时显示时间
```javascript
window.onload = function() {
document.write(new Date().toLocaleString());
};
```
5. 定时刷新页面
```javascript
setInterval(function() {
location.reload();
}, 60000); // 每60秒刷新一次
```
二、动画与过渡效果
6. 淡入淡出动画
```javascript
function fadeIn(element) {
element.style.opacity = 0;
var last = +new Date();
var tick = function() {
element.style.opacity = +element.style.opacity + (new Date() - last) / 200;
last = +new Date();
if (+element.style.opacity < 1) {
requestAnimationFrame(tick);
}
};
requestAnimationFrame(tick);
}
```
7. 元素平滑滚动到顶部
```javascript
function scrollToTop() {
window.scrollTo({ top: 0, behavior: 'smooth' });
}
```
8. 按钮点击动效
```javascript
document.getElementById("btn").addEventListener("click", function() {
this.classList.add("active");
setTimeout(() => this.classList.remove("active"), 300);
});
```
9. 图片轮播效果
```javascript
let index = 0;
const images = ["img1.jpg", "img2.jpg", "img3.jpg"];
function changeImage() {
document.getElementById("slide").src = images[index];
index = (index + 1) % images.length;
}
setInterval(changeImage, 2000);
```
10. 悬浮菜单展开/收起
```javascript
document.querySelector(".menu").addEventListener("mouseover", function() {
this.style.height = "100px";
});
document.querySelector(".menu").addEventListener("mouseout", function() {
this.style.height = "0";
});
```
三、表单与用户交互
11. 表单验证(必填项)
```javascript
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("姓名不能为空");
return false;
}
}
```
12. 密码强度检测
```javascript
function checkPasswordStrength(password) {
let strength = 0;
if (password.length > 6) strength += 1;
if (password.match(/[a-z]/)) strength += 1;
if (password.match(/[A-Z]/)) strength += 1;
if (password.match(/\d/)) strength += 1;
if (password.match(/[^a-zA-Z\d]/)) strength += 1;
return strength;
}
```
13. 下拉菜单动态加载选项
```javascript
const select = document.getElementById("city");
const cities = ["北京", "上海", "广州", "深圳"];
cities.forEach(city => {
const option = document.createElement("option");
option.value = city;
option.text = city;
select.appendChild(option);
});
```
14. 实时搜索建议
```javascript
const input = document.getElementById("search");
const suggestions = ["苹果", "香蕉", "橘子", "葡萄"];
input.addEventListener("input", () => {
const value = input.value.toLowerCase();
const filtered = suggestions.filter(s => s.toLowerCase().includes(value));
console.log(filtered);
});
```
15. 文件上传预览
```javascript
function previewFile(input) {
const file = input.files[0];
const reader = new FileReader();
reader.onload = function(e) {
document.getElementById("preview").src = e.target.result;
};
reader.readAsDataURL(file);
}
```
四、数据操作与DOM控制
16. 动态创建表格行
```javascript
const table = document.getElementById("myTable");
const row = table.insertRow();
const cell1 = row.insertCell(0);
const cell2 = row.insertCell(1);
cell1.innerHTML = "新行1";
cell2.innerHTML = "新行2";
```
17. 删除指定DOM元素
```javascript
function removeElement(id) {
const element = document.getElementById(id);
if (element) {
element.remove();
}
}
```
18. 获取并修改元素样式
```javascript
const div = document.getElementById("myDiv");
div.style.color = "red";
div.style.fontSize = "20px";
```
19. 获取URL参数
```javascript
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
const regex = new RegExp('[?&]' + name + '(=([^&])|&||$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
```
20. 动态加载外部JS脚本
```javascript
function loadScript(src) {
const script = document.createElement('script');
script.src = src;
document.head.appendChild(script);
}
```
五、高级特效与实用功能
21. 拖拽元素移动
```javascript
const drag = document.getElementById("dragMe");
let offsetX, offsetY;
drag.addEventListener("mousedown", function(e) {
offsetX = e.offsetX;
offsetY = e.offsetY;
document.addEventListener("mousemove", onMouseMove);
document.addEventListener("mouseup", onMouseUp);
});
function onMouseMove(e) {
drag.style.left = (e.pageX - offsetX) + "px";
drag.style.top = (e.pageY - offsetY) + "px";
}
function onMouseUp() {
document.removeEventListener("mousemove", onMouseMove);
document.removeEventListener("mouseup", onMouseUp);
}
```
22. 粒子特效(简单模拟)
```javascript
const canvas = document.getElementById("particleCanvas");
const ctx = canvas.getContext("2d");
class Particle {
constructor(x, y) {
this.x = x;
this.y = y;
this.radius = Math.random() 3 + 1;
this.speedX = Math.random() 2 - 1;
this.speedY = Math.random() 2 - 1;
}
update() {
this.x += this.speedX;
this.y += this.speedY;
if (this.x < 0 || this.x > canvas.width) this.speedX = -1;
if (this.y < 0 || this.y > canvas.height) this.speedY = -1;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI 2);
ctx.fillStyle = "white";
ctx.fill();
}
}
const particles = [];
for (let i = 0; i < 100; i++) {
particles.push(new Particle(Math.random() canvas.width, Math.random() canvas.height));
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let p of particles) {
p.update();
p.draw();
}
requestAnimationFrame(animate);
}
animate();
```
23. 倒计时功能
```javascript
function countdown(endTime) {
const now = new Date().getTime();
const distance = endTime - 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 + "天 " + hours + "小时 " + minutes + "分 " + seconds + "秒 ";
}
setInterval(countdown, 1000);
```
24. 复制文本到剪贴板
```javascript
function copyText(text) {
navigator.clipboard.writeText(text).then(() => {
alert("复制成功!");
}).catch(err => {
alert("复制失败: " + err);
});
}
```
25. 生成随机颜色
```javascript
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() 16)];
}
return color;
}
```
六、总结
以上只是 JavaScript 特效代码大全(420 个) 中的一部分内容。这些代码涵盖了从基础到进阶的多种应用场景,适合不同层次的开发者进行学习和实践。通过不断积累和优化这些代码片段,可以显著提高前端开发效率,并为网站增添更多生动的交互体验。
如果你正在寻找一个全面的 JavaScript 效果资源库,这份列表将是一个不错的起点。无论是用于项目开发、教学演示还是个人练习,都可以从中获得极大的帮助。
> 提示:实际应用中,请根据具体需求调整代码逻辑,并注意兼容性与性能优化。