1、如何获取当前页面的滚动位置
const getScrollPosition = (el = window) => ({
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});
// 事例
getScrollPosition(); // {x: 0, y: 200}
2、如何平滑的滚动到页面顶部
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
}
// 事例
scrollToTop()
小笔记: window.requestAnimationFrame() 告诉浏览器——你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。该方法需要传入一个回调函数作为参数,该回调函数会在浏览器下一次重绘之前执行。
requestAnimationFrame:优势:由系统决定回调函数的执行时机。60Hz的刷新频率,那么每次刷新的间隔中会执行一次回调函数,不会引起丢帧,不会卡顿。
3、如何检查指定元素在视口中是否可见
const elementIsVisibleInViewport = (el, partiallyVisible) => { //partiallyVisible 是否部分可见
const { top, right, bottom, left } = el.getBoundingClientRect();
const { innerWidth, innerHeight } = window;
return partiallyVisible
? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
: top >= 0 && bottom <= innerHeight && left >= 0 && right <= innerWidth;
}
//示例
elementIsVisibleInViewport(document.querySelector(".top"), false);//false表示全部可见
elementIsVisibleInViewport(document.querySelector(".top"), true);//true表示部分可见
4、如何获取元素中所有的图像
const getImages = (el, includeDuplicates) => {//includeDuplicates 是否包含重复图片
const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src'));
// return includeDuplicates ? images : Array.from(new Set(images))
return includeDuplicates ? images : [...new Set(images)]
}
getImages(document, true);
getImages(document, false);
5、如何确定设备是移动设备还是台式机/笔记本电脑
const detectDeviceType = () =>
/Android|webOs|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
? 'Mobile'
: 'Desktop';
// 事例
detectDeviceType(); // "Mobile" or "Desktop"
6、如何创建一个包含当前url参数的对象(*)
const getURLParameters = url =>
(url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
(a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
{}
);
// 事例
getURLParameters('http://url.com/page?n=Adam&s=Smith'); // {n: 'Adam', s: 'Smith'}
getURLParameters('google.com'); // {}
小笔记: (a, v) => ((a[v.slice(0, v.indexOf(’=’))] = v.slice(v.indexOf(’=’) + 1)), a) ,这个事件使用了 逗号运算符,逗号运算符是二元运算符,它能够先执行运算符左侧的操作数,然后再执行右侧的操作数,最后返回右侧操作数的值。因此以上代码可等价于:
const getURLParameters = url =>
(url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
(a, v) => {
(a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1));
return a
},
{}
);
// 事例
getURLParameters('http://url.com/page?n=Adam&s=Smith'); // {n: 'Adam', s: 'Smith'}
getURLParameters('google.com'); // {}
补充一点: reduce()函数使用语法:array.reduce(function(total, currentValue, currentIndex, arr), initialValue),reduce方法详细文档
7、如何获得给定毫秒数的可读格式
const formatDuration = ms => {
if (ms < 0) ms = -ms;
const time = {
day: Math.floor(ms / 86400000),
hour: Math.floor(ms / 3600000) % 24,
minute: Math.floor(ms / 60000) % 60,
second: Math.floor(ms / 1000) % 60,
millisecond: Math.floor(ms) % 1000
};
return Object.entries(time)
.filter(val => val[1] !== 0)
.map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`)
.join(', ');
};
// 事例
formatDuration(1001); // '1 second, 1 millisecond'
formatDuration(34325055574);
// '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'
8、如何获得两个日期之间的差异(以天为单位)
const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
(dateFinal - dateInitial) / (1000 * 3600 * 24);
// 事例
getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); // 9
// '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'
9、如何为指定选择器创建具有指定范围,步长和持续时间的计数器?
const counter = (selector, start, end, step = 1, duration = 2000) => {
let current = start,
_step = (end - start) * step < 0 ? -step : step,
timer = setInterval(() => {
current += _step;
document.querySelector(selector).innerHTML = current;
if (current >= end) document.querySelector(selector).innerHTML = end;
if (current >= end) clearInterval(timer);
}, Math.abs(Math.floor(duration / (end - start))));
return timer;
};
// 事例
counter('#my-id', 1, 1000, 5, 2000);
// 让 `id=“my-id”`的元素创建一个2秒计时器