html方法收集
文章目录
- 检测网络速度
- 为移动端应用添加振动反馈
- 禁止文本粘贴
- 隐藏 DOM 元素
- 使用 inset 简化定位
- console 调试
- 防止移动端下拉刷新
- 让网页可编辑
- 使用 ID 生成全局变量
- 平滑滚动效果
- 使用 :empty 选择器隐藏空元素
- 日期处理函数
- 获取一周开始和结束日期,周一为第一天
- 对象属性值转数组
- 从数组中获取随机元素
- 截取小数点后指定位数
- 获取URL参数
检测网络速度
//通过 JavaScript 的 Network Information API,检测网络下载速度
if (navigator.connection) {
const downlink = navigator.connection.downlink;
console.log(`当前下载速度: ${downlink} Mbps`);
} else {
console.log("Network Information API 不被支持");
}
为移动端应用添加振动反馈
/ 振动 500 毫秒
if (navigator.vibrate) {
navigator.vibrate(500);
} else {
console.log("Vibrate API 不被支持");
}
// 创建振动和暂停的模式
if (navigator.vibrate) {
navigator.vibrate([200, 100, 200, 100, 200]);
}
禁止文本粘贴
<input type="text" id="text-input" />
<script>
const input = document.getElementById('text-input');
input.addEventListener("paste", function(e){
e.preventDefault();
alert("禁止粘贴内容!");
});
</script>
隐藏 DOM 元素
<!--属性与 display: none; 类似,会让元素从页面中消失。-->
<p hidden>这个文本是不可见的</p>
使用 inset 简化定位
/* 原始方法 */
div {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
/* 使用 inset 简化 */
div {
position: absolute;
inset: 0;
}
console 调试
//console.table():以表格形式展示数组或对象:
const data = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 }
];
console.table(data);
//console.group() 和 console.groupEnd():将相关的日志进行分组:
console.group('调试日志');
console.log('消息 1');
console.log('消息 2');
console.groupEnd();
//console.time() 和 console.timeEnd():测量代码执行的时间:
console.time('代码运行时间');
// 模拟耗时代码
console.timeEnd('代码运行时间');
//添加样式
console.log('\x1b[36m%s\x1b[0m', '36代表青色,\x1b[0m重置样式');
console.log('\x1b[43m\x1b[31m%s\x1b[0m', '43是黄色背景,31是红色字体');
//(注:\x1b[36m是ANSI转义码,36代表青色,43是黄色背景,31是红色字体,%s用来占位,\x1b[0m重置样式)
//控制台背景
console.log(
'%c样式1 %c样式2',
'background: linear-gradient(45deg, #ff6b6b, #4ecdc4); padding: 5px 10px; border-radius: 3px; color: white;',
'background: linear-gradient(45deg, #fdcb6e, #e17055); padding: 5px 10px; border-radius: 3px;')
//动态Debug
function logWithStyle(type, message) {
const styles = {
error: 'color: red; font-weight: bold; background: #ffe5e5; padding: 2px 5px;',
warn: 'color: orange; background: #fff3e0; padding: 2px 5px;',
success: 'color: green; background: #e8f5e9; padding: 2px 5px;',
debug: 'color: #666; background: #f5f5f5; padding: 2px 5px;'
};
console.log(`%c${type.toUpperCase()} ➤ ${message}`, styles[type]);
}
// 用法:
logWithStyle('error', '这是一个Bug!'); // 红色警告
logWithStyle('success', 'Bug已祭天!'); // 绿色嘚瑟
防止移动端下拉刷新
body {
overscroll-behavior-y: contain;
}
让网页可编辑
document.body.contentEditable = 'true';
使用 ID 生成全局变量
<div id="myDiv">Hello</div>
<script>
console.log(myDiv); // 自动生成全局变量 myDiv
</script>
平滑滚动效果
html {
scroll-behavior: smooth;
}
使用 :empty 选择器隐藏空元素
p:empty {
display: none;
}
日期处理函数
//判断格式化参数并进行预处理
//根据传入的格式化参数,返回一个具体的格式化函数。
//如果传入的是 'date',就转换为 'yyyy-MM-dd' 格式;
//如果是 'datetime',就转换为 'yyyy-MM-dd HH:mm:ss' 格式。
function _formatNormailze(formatter) {
if (typeof formatter === 'function') {
return formatter;
}
if (typeof formatter !== 'string') {
throw new TypeError('formatter is not string');
}
if (formatter === 'date') {
formatter = 'yyyy-MM-dd';
}
if (formatter === 'datetime') {
formatter = 'yyyy-MM-dd HH:mm:ss';
}
const formatterFunc = (dateInfo) => {
const { yyyy, MM, dd, HH, mm, ss, ms } = dateInfo;
let formatted = formatter
.replace("yyyy", yyyy)
.replaceAll("MM", MM)
.replaceAll("dd", dd)
.replace("HH", HH)
.replace("mm", mm)
.replace("ss", ss)
.replace("ms", ms);
return formatted;
};
return formatterFunc;
}
//接收日期、格式化参数和是否补零的参数
function formate(date, formatter, isPad = true) {
const formatFunc = _formatNormailze(formatter);
const dateInfo = {
yyyy: date.getFullYear().toString(),
MM: (date.getMonth() + 1).toString(),
dd: date.getDate().toString(),
HH: date.getHours().toString(),
mm: date.getMinutes().toString(),
ss: date.getSeconds().toString(),
ms: date.getMilliseconds().toString()
};
function _pad(prop, len) {
//用于给时间部分补零
dateInfo[prop] = dateInfo[prop].padStart(len, '0');
}
if (isPad) {
_pad('yyyy', 4);
_pad('MM', 2);
_pad('dd', 2);
_pad('HH', 2);
_pad('mm', 2);
_pad('ss', 2);
_pad('ms', 3);
}
const result = formatFunc(dateInfo);
return result;
}
const now = new Date();
// 示例 1:格式化为日期
console.log(formate(now, 'date')); // 输出类似 "2023-04-10"
// 示例 2:格式化为日期时间
console.log(formate(now, 'datetime')); // 输出类似 "2023-04-10 23:59:59"
// 示例 3:格式化为自定义格式,并补零
console.log(formate(now, 'yyyy/MM/dd HH:mm', true)); // 输出类似 "2023/04/10 23:59"
获取一周开始和结束日期,周一为第一天
function getCurrentWeekDates(type,start,end){
let currentDate = null
if (type == 'before') {
currentDate = new Date(new Date(start).getTime() - 7 * 24 * 3600 * 1000)
} else if (type == 'after') {
currentDate = new Date(new Date(end).getTime() + 1 * 24 * 3600 * 1000)
} else {
currentDate = new Date()
}
const currentDayOfWeek = currentDate.getDay()
const diff = currentDate.getDate() - currentDayOfWeek + (currentDayOfWeek === 0 ? -6 : 1); // 计算周一的日期偏移量
// 获取周一的日期
const monday = new Date(currentDate.setDate(diff));
// 获取周日的日期
const sunday = new Date(currentDate.setDate(diff + 6));
// 将日期转换为 YYYY-MM-DD 格式
let startdate = formate(monday, 'date')
let enddate = formate(sunday, 'date')
return {startdate,enddate}
}
对象属性值转数组
const values = Object.values(object);
从数组中获取随机元素
const randomElement = array[Math.floor(Math.random() * array.length)];
截取小数点后指定位数
const toFixed = num => Math.round(num * 100) / 100; // 保留两位小数
获取URL参数
const params = Object.fromEntries(new URLSearchParams(window.location.search));
原文链接1
原文链接2