JS代码片段(Browser)
Browser
copyToClipboard
将一个字符串复制到剪贴板。仅作为用户操作的结果(即,在click
事件侦听器中)。
创建一个新的<textarea>
元素,用提供的数据填充它,并将其添加到HTML文档中。使用Selection.getRangeAt()
来存储选择的范围(如果有的话)。使用document.execCommand('copy')
复制到剪贴板。从HTML文档中删除<textarea>
元素。最后,使用Selection().addRange()
来恢复原始选择范围(如果有的话)。
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);
}
};
copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.
createElement
根据一个字符串创建一个元素(不附加到document
)。如果给定的字符串包含多个元素,则只返回第一个元素。
使用document.createElement()
来创建一个新的元素。 将它的innerHTML
设置为作为参数提供的字符串。使用ParentNode.firstElementChild
来返回字符串的元素版本。
const createElement = str => {
const el = document.createElement('div');
el.innerHTML = str;
return el.firstElementChild;
};
const el = createElement(
`<div class="container">
<p>Hello!</p>
</div>`
);
console.log(el.className); // 'container'
currentURL
返回当前页面URL。
使用window.location.href
获取当前页面URL。
const currentURL = () => window.location.href;
currentURL(); // 'https://google.com'
detectDeviceType
检测网站是否正在移动设备或台式机/笔记本电脑上打开。
使用正则表达式来测试navigator.userAgent
属性以确定打开设备是移动设备还是台式机/笔记本电脑。
const detectDeviceType = () =>
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
? 'Mobile'
: 'Desktop';
detectDeviceType(); // "Mobile" or "Desktop"
elementIsVisibleInViewport
如果指定的元素在可视窗口中可见,则返回true
,否则返回false
。
使用Element.getBoundingClientRect()
和window.inner(Width|Height)
值来确定给定元素是否在可视窗口中可见。省略第二个参数来判断元素是否完全可见,或者指定true
来判断它是否部分可见。
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;
};
// e.g. 100x100 viewport and a 10x10px element at position {top: -1, left: 0, bottom: 9, right: 10}
elementIsVisibleInViewport(el); // false - (not fully visible)
elementIsVisibleInViewport(el, true); // true - (partially visible)
getScrollPosition
返回当前页面的滚动位置。
如果浏览器支持pageXOffset
和pageYOffset
,那么请使用pageXOffset
和pageYOffset
,否则请使用scrollLeft
和scrollTop
。 你可以省略el
参数,默认值为window
。
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}
getStyle
返回指定元素的CSS规则的值。
使用Window.getComputedStyle()
获取指定元素的CSS规则的值。
const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];
getStyle(document.querySelector('p'), 'font-size'); // '16px'
hasClass
如果元素具有指定的样式类,则返回true
;否则返回false
。
使用element.classList.contains()
检查元素是否具有指定的样式类。
const hasClass = (el, className) => el.classList.contains(className);
hasClass(document.querySelector('p.special'), 'special'); // true
hide
隐藏所有指定的元素。
使用展开运算符(...
)和Array.forEach()
将display: none
应用于每个指定的元素。
const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));
hide(document.querySelectorAll('img')); // Hides all <img> elements on the page
httpsRedirect
如果其当前使用HTTP访问,则将页面重定向到HTTPS中。 另外,按下后退按钮不会将其退回到历史记录中的HTTP页面。
使用location.protocol
获取当前正在使用的协议。 如果不是HTTPS,使用location.replace()
将现有页面替换为HTTPS版本。 使用location.href
获取完整的地址,用String.split()
拆分完整的地址,并移除URL的协议部分。
const httpsRedirect = () => {
if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]);
};
httpsRedirect();
// If you are on http://mydomain.com, you are redirected to https://mydomain.com
redirect
重定向到一个URL 。
使用window.location.href
或window.location.replace()
重定向到url
。 传递第二个参数来模拟链接点击(true
- 默认值)或HTTP重定向(false
)。
const redirect = (url, asLink = true) =>
asLink ? (window.location.href = url) : window.location.replace(url);
redirect('https://google.com');
scrollToTop
平滑滚动到页面顶部。
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
};
scrollToTop();
setStyle
设置指定元素CSS规则的值。
使用element.style
将指定元素的CSS规则的值设置为val
。
const setStyle = (el, ruleName, val) => (el.style[ruleName] = val);
setStyle(document.querySelector('p'), 'font-size', '20px');
show
显示所有指定的元素。
const show = (...el) => [...el].forEach(e => (e.style.display = ''));
show(...document.querySelectorAll('img'));
smoothScroll
平滑地将调用它的元素滚动到浏览器窗口的可见区域。
const smoothScroll = element =>
document.querySelector(element).scrollIntoView({
behavior: 'smooth'
});
smoothScroll('#fooBar');
smoothScroll('.fooBar');
// scrolls smoothly to the first element with a class of fooBar
toggleClass
切换一个元素的样式类。
使用element.classList.toggle()
来切换元素中指定样式类。
const toggleClass = (el, className) => el.classList.toggle(className);
toggleClass(document.querySelector('p.special'), 'special');
// The paragraph will not have the 'special' class anymore