将字符串复制到剪贴板
- const copyToClipboard = str => {
- const el = document.createElement(‘textarea’);
- el.value = str;
- el.setAttribute(‘readonly’, ”);
- el.style.position = ‘absolute’;
- el.style.left = ‘-100%’;
- 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(‘195440.com’); // ‘195440.com’ copied to clipboard.
判断元素是否在可视窗口可见
使用 Element.getBoundingClientRect()
和 window.inner(Width|Height)
值来确定给定元素是否在可视窗口中可见。 省略第二个参数来判断元素是否完全可见,或者指定 true
来判断它是否部分可见。
- const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
- const { top, left, bottom, right } = el.getBoundingClientRect();
- 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) -> false (not fully visible)
- elementIsVisibleInViewport(el, true) -> true (partially visible)
在给定元素上触发特定事件,并可选地传递自定义数据
- const triggerEvent = (el, eventType, detail) =>
- el.dispatchEvent(new CustomEvent(eventType, { detail }));
- // 例子
- triggerEvent(document.getElementById(‘myId’), ‘click’);
- triggerEvent(document.getElementById(‘myId’), ‘click’, { username: ‘bob’ });
链式调用异步函数
循环遍历包含异步事件的函数数组,每次异步事件完成后调用 next
。
- const chainAsync = fns => { let curr = 0; const next = () => fns[curr++](next); next(); };
- chainAsync([
- next => { console.log(‘0 seconds’); setTimeout(next, 1000); },
- next => { console.log(‘1 second’); setTimeout(next, 1000); },
- next => { console.log(‘2 seconds’); }
- ])
运行连续的 promise
使用 Array.reduce()
通过创建 promise 链来运行连续的 promises,
其中每个 promise 在 resolved 时返回下一个 promise 。
- const series = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
- const delay = (d) => new Promise(r => setTimeout(r, d));
- series([() => delay(1000), () => delay(2000)]);
本文链接地址: 实用ES6代码片段