24个解决实际问题的ES6代码片段(小结)(3)

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; }; // Example counter('#my-id', 1, 1000, 5, 2000); // Creates a 2-second timer for the element with

22.如何将字符串复制到剪贴板

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.

document.getSelection()返回一个  Selection 对象,表示用户选择的文本范围或光标的当前位置。

23.判断页面的浏览器选项卡是否聚焦

const isBrowserTabFocused = () => !document.hidden; // Example isBrowserTabFocused(); // true

24.如果不存在目录,则如何创建

const fs = require('fs'); const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined); // Example createDirIfNotExists('test'); // creates the directory

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/10bdfdd8f39a965ffd48bc4b5d413960.html