// 假设设计稿基准宽度为750px,将屏幕宽度逻辑上分成10份;
function applyTaobaoAdaptive() {
const docEl = document.documentElement;
const baseWidth = 750;
const winWidth = docEl.clientWidth || window.innerWidth;
const onePartwidth = winWidth / 10;
docEl.style.fontSise = onePartwidth + "px";
}
//监听窗口大小变化,实时更新适应
// applyTaobaoAdaptive();
// window.addEventListener('resize',applyTaobaoAdaptive());
// 防抖 (高频,耗时,最后一次调用为准)
function debounce(fn, delay = 1000) {
let timerTd;
return function (...args) {
clearInterval(timerTd);
timerTd = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
const d_layout = debounce(applyTaobaoAdaptive, 500);
window.addEventListener("resize", d_layout);
// Window.onresize=d_layout;
// 节流(高频,规定时间内只执行一次)
// lodash js中间件
// 1声明一个定时器变量
// 2每次调用判断定时器是否开启,有就不开定时器了
// 3没有定时器就开启定时器,记得存变量
// 3.1定时器里调用要执行的函数
// 3.2定时器里面要把定时器清空
// 假设一个模拟场景:鼠标悬浮事件
const box = document.getElementById("nihao");
var i = 0;
function mouseMove() {
box.innerHTML = i++;
}
// box.addEventListener('mousemove',mouseMove)
// 防抖事件
function throttle(fn, t) {
let timer = null;
return function () {
if (!timer) {
timer = setTimeout(function () {
fn();
// 清空定时器
timer = null;
}, t);
}
};
}
box.addEventListener("mousemove",throttle(mouseMove,1000));
最开始这个屏幕自适应是我用在uniapp上的一个方法,现在放在vue中做手机端的开发效果也还可以大家可以试试;
防抖和节流网上其实一大堆:
防抖:适用于高频调用的耗时任务,而且以最后一次调用时间为准
节流:节流的场景适用于高频任务,规定时间只执行一次,中间触发的不生效;