-
如何获取当前页面的滚动位置?
const getScrollPosition = (el = window) => ({
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});
// Example
getScrollPosition(); // {x: 0, y: 200}
-
如何平滑滚动到页面顶部?
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
};
// Example
scrollToTop();
-
如何确认指定元素是否在视口可见?
const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
const { top, left, bottom, right } = el.getBoundingClientRect();
const { innerHeight, innerWidth } = window;
return partiallyVisible
? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
};
// Examples
elementIsVisibleInViewport(el); // (不完全可见)
elementIsVisibleInViewport(el, true); // (部分可见)
-
如何分辨设备是移动设备还是桌面设备?
const detectDeviceType = () =>
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
? 'Mobile'
: 'Desktop';
// Example
detectDeviceType(); // "Mobile" or "Desktop"
-
如何解析包含当前 URL 参数的对象?
const getURLParameters = url =>
(url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
(a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
{}
);
// Examples
getURLParameters('http://url.com/pagen=Adam&s;=Smith'); // {n: 'Adam', s: 'Smith'}
getURLParameters('google.com'); // {}
-
如何将一个字符串复制到剪贴板?
const copyToClipboard = str => {
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
const selected = document.getSelection().rangeCount > 0 ?
document.getSelection().getRangeAt(0) : false;
el.select();
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
};
// Example
copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.
-
如何确定页面的浏览器选项卡是否处于前台活跃状态?
const isBrowserTabFocused = () => !document.hidden;
// Example
isBrowserTabFocused(); // true
-
使用 setTimeout 模拟 setInterval
// 定义
let timer = null;
function interval(func, wait){
let interv = function(){
func.call(null); // 执行传入函数
timer=setTimeout(interv, wait); // 执行完成后再次触发setTimeout定时器
};
timer= setTimeout(interv, wait); // 初始化,启动timer
}
// 使用
interval(function() {}, 20);
// 停止
if (timer) {
window.clearSetTimeout(timer);
timer = null;
}
// 参考文章:
// https://mp.weixin.qq.com/s/l9tyHzQ0O68m1rzwWCJmMw