1.如何隐藏所有指定的元素
2.如何检查元素是否具有指定的类?
const hasClass = (el, className) => el.classList.contains(className)// 事例hasClass(document.querySelector('p.special'),'special') //true
3.如何切换一个元素的类?
const toggleClass = (el, className) => el.classList.toggle(className)// 事例 移除 p 具有类`special`的 special 类toggleClass(document.querySelector('p.special'),'special')
4.如何获取当前页面的滚动位置?
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}
5.如何平滑滚动到页面顶部
const scrollToTop = () => { const c = document.documentElement.scrollTop || document.body.scrollTop;if(c > 0) { window.requestAnimationFrame(scrollToTop); window.scrollTo(0, c - c / 8); }}
//scrollToTop()
6.如何检查父元素是否包含子元素?
const elementContains = (parent, child) => parent !== child && parent.contains(child);// 事例elementContains(document.querySelector('head'), document.querySelector('title')); //true
elementContains(document.querySelector('body'), document.querySelector('body')); //false
7.如何检查指定的元素在视口中是否可见?
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;};
// 事例elementIsVisibleInViewport(el);// 需要左右可见
elementIsVisibleInViewport(el,true); // 需要全屏(上下左右)可以见
网友评论