返回
自创无限乐趣,JavaScript超强功能合集(续)
前端
2023-09-12 20:11:53
JavaScript——在简单功能中发现无限乐趣
继上次分享的一些实用小功能后,我们继续这次的JavaScript之旅,探索更多有意思的功能。
1. 高效倒计时:
- 利用Date和setInterval函数,轻松实现一个可定制的倒计时,使您的页面充满互动性和紧迫感。
-
// 设置目标日期 const targetDate = new Date("2023-12-31 23:59:59"); // 定义倒计时函数 const countdown = () => { // 计算剩余时间 const now = new Date(); const diff = targetDate - now; // 格式化时间 const days = Math.floor(diff / (1000 * 60 * 60 * 24)); const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)); const seconds = Math.floor((diff % (1000 * 60)) / 1000); // 显示倒计时 document.getElementById("countdown").innerHTML = days + "天 " + hours + "时 " + minutes + "分 " + seconds + "秒"; // 递归调用函数以持续更新倒计时 setTimeout(countdown, 1000); }; // 启动倒计时 countdown();
**2. 动态图像展示:**
- 将图像加载到画布元素中,并使用requestAnimationFrame()方法持续更新,呈现出令人惊叹的动态图像效果。
- ```javascript
// 获取画布元素
const canvas = document.getElementById("canvas");
// 创建画布上下文
const ctx = canvas.getContext("2d");
// 加载图像
const image = new Image();
image.src = "image.png";
// 持续更新图像
const draw = () => {
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制图像
ctx.drawImage(image, 0, 0);
// 使用requestAnimationFrame()持续更新图像
requestAnimationFrame(draw);
};
// 启动图像更新
draw();
3. 随机数字生成器:
- 创建一个生成随机数字的函数,您可以指定范围,函数将为您生成该范围内的随机整数。
-
// 创建随机数生成函数 const randomNumber = (min, max) => { // 确保min和max为数字 min = parseInt(min); max = parseInt(max); // 计算随机数 const random = Math.floor(Math.random() * (max - min + 1)) + min; // 返回随机数 return random; };
**4. 字符串倒转:**
- 编写一个函数,可以反转一个字符串,使您轻松处理字符串操作。
- ```javascript
// 创建字符串反转函数
const reverseString = (str) => {
// 创建一个空字符串
let reversed = "";
// 从字符串末尾开始遍历
for (let i = str.length - 1; i >= 0; i--) {
// 将每个字符添加到reversed字符串中
reversed += str[i];
}
// 返回反转后的字符串
return reversed;
};
5. 动态加载外部脚本:
- 在JavaScript中,您可以动态加载外部脚本文件,从而实现按需加载资源。
-
// 创建一个新脚本元素 const script = document.createElement("script"); // 设置脚本的src属性,指向要加载的外部脚本文件 script.src = "external-script.js"; // 将脚本元素添加到文档中 document.head.appendChild(script);
**结语**
以上这些小功能仅是JavaScript强大功能的冰山一角,希望它们能够为您的项目带来更多趣味和实用性。如果您有更多好玩的功能,欢迎在评论区分享!