30个有用的JavaScript代码片段(下)

今天这篇文章,接上昨天的《30 个有用的 JavaScript 代码片段(上)》,我们把剩下的18个代码片段分享在这篇文章中。

现在,我们就开始这篇文章的内容吧。

13. 创建一个 DOM 元素

// Code snippet to render  DOM element on the fly
const loadImage = (url) => new Promise((resolve, reject) => {
    const img = new Image();
    img.addEventListener('load', () => resolve(img));
    img.addEventListener('error', (err) => reject(err));
    img.src = url;
});
// __USAGE Example__
var uploadFileInput=document.createElement('input');
uploadFileInput.type='file';
uploadFileInput.id='uploadFileInput';
document.body.appendChild(uploadFileInput);


function readFileAsDataURL(file) {
    return new Promise((resolve,reject) => {
        let fileredr = new FileReader();
        fileredr.onload = () => resolve(fileredr.result);
        fileredr.onerror = () => reject(fileredr);
        fileredr.readAsDataURL(file);
    });
}


uploadFileInput.addEventListener('change', async (evt)=> {
  var file = evt.currentTarget.files[0];
    if(!file) return;


    var b64str = await readFileAsDataURL(file);
    var _img = await loadImage(b64str);
    _img['style']['width']=`${_img.naturalWidth}px`;
    _img['style']['height']=`${_img.naturalHeight}px`;
    _img['style']['margin']='2px auto';
    _img['style']['display']='block';
    document.body.appendChild(_img);
}, false);

注意:虽然大多数 HTML 元素节点的属性(例如

)是可访问的并且不需要“load”事件的侦听器,但 是此规则的一个例外(另一个唯一的例外是 < 脚本>)

因此,如果 document.createElement('img') 没有返回 Promise:

var loadedImg=document.createElement('img');
loadedImg.src=; // dataURL refers to the encoded image data

变量loadedImg不会被渲染,因为在分配属性src时它仍然是未定义的。

14. 删除所有嵌套子节点

const removeAllChildNodes = ((parentEle) => parentEle.children.length > 0  ? parentEle.removeChild(parentEle.children[0]) : null);
// __USAGE Example__
const _scale = window.devicePixelRatio*2;
const size = 250;
const fontSize=size/_scale;


var canvasDisplay=document.createElement('div');
canvasDisplay['style']['width']=`${size+4}px`;
canvasDisplay['style']['height']=`${size+4}px`;
canvasDisplay['style']['margin']='1px auto';
document.body.appendChild(canvasDisplay);


var iconBtn_1=document.createElement('button');
iconBtn_1.type='button';
iconBtn_1.value='';
iconBtn_1.innerText='';
document.body.appendChild(iconBtn_1);


var iconBtn_2=document.createElement('button');
iconBtn_2.type='button';
iconBtn_2.value='';
iconBtn_2.innerText='';
document.body.appendChild(iconBtn_2);


function setIcon(icon) {
  var canvas=document.createElement('canvas');
  canvas.width=size;
  canvas.height=size;
  canvas['style']['margin']='1px auto';
  canvas['style']['width']=`${fontSize}px`;
  canvas['style']['height']=`${fontSize}px`;
  canvas['style']['border']='1px dotted #6c757d';
  canvas['style']['background']='transparent';


  var ctx=canvas.getContext('2d');
  ctx.scale(_scale,_scale);
  ctx.font = `${fontSize}px Segoe Ui Emoji`;
  ctx.textAlign = 'center';
  ctx.textBaseline='middle';
  ctx.globalAlpha=1.0;
  ctx.fontVariantCaps='unicase';
  ctx.filter='none';
  ctx.globalCompositeOperation='source-over';
  ctx.imageSmoothingEnabled=true;
  ctx.imageSmoothingQuality='high';
  ctx.letterSpacing='0px';
  ctx.lineWidth=0;
  ctx.shadowColor='rgba(0, 0, 0, 0)';
  ctx.strokeStyle='#000000';
  ctx.fillStyle='#ffffff';


  const _x=((canvas.width/_scale)/2);
  const _y=((canvas.height/_scale)/2);
  ctx.fillText(icon, _x, _y);


  removeAllChildNodes(canvasDisplay);
  canvasDisplay.appendChild(canvas);
}


iconBtn_1.addEventListener('click', ()=> {
  setIcon(iconBtn_1.value);
});
iconBtn_2.addEventListener('click', ()=> {
  setIcon(iconBtn_2.value);
});

使用示例:

注意:函数removeAllChildNodes()使用递归来删除所有嵌套元素。这对于防止先前不需要的子节点与后续附加的子节点累积是必要的,如下所示:

15. 选择文本并将其复制到剪贴板 — 表单输入和其他 HTML DOM 元素

function selectCopyText(nodeId) {
    let isVal=true;
    let node = document.getElementById(nodeId);
    try {
        node.select();
        try { node.setSelectionRange(0, 99999);} catch(err0) {}
    } catch(err) {
        isVal=false;
        if (document.body.createTextRange) {
            const range = document.body.createTextRange();
            range.moveToElementText(node);
            range.select();
        } else if (window.getSelection) {
            const selection = window.getSelection();
            const range = document.createRange();
            range.selectNodeContents(node);
            selection.removeAllRanges();
            selection.addRange(range);
        } else { console.warn("Could not select text in node: Unsupported browser."); }
    } finally { navigator.clipboard.writeText(isVal ? node.value : node.innerText);}
}
const strToCopy = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Viverra accumsan in nisl nisi scelerisque eu ultrices. Posuere lorem ipsum dolor sit amet consectetur adipiscing. Sodales ut etiam sit amet nisl purus.';


var _copyBtn=document.createElement('button');
_copyBtn.type='button';
_copyBtn.value='toCopy';
_copyBtn.innerText='Copy Textarea';


var _textarea=document.createElement('textarea');
_textarea.id='toCopy';
_textarea['style']['resize']='none';
_textarea['style']['width']='100%';
_textarea['style']['height']='100px';
_textarea['style']['display']='block';
_textarea.value=strToCopy;
document.body.appendChild(_copyBtn);
document.body.appendChild(_textarea);


var _copyBtn2=document.createElement('button');
_copyBtn2.type='button';
_copyBtn2.value='toCopy2';
_copyBtn2.innerText='Copy DIV';


var _div=document.createElement('_div');
_div.id='toCopy2';
_div['style']['width']='100%';
_div['style']['height']='100px';
_div['style']['display']='block';
_div['style']['border']='1px dashed #000000';
_div.innerText=strToCopy;
document.body.appendChild(_copyBtn2);
document.body.appendChild(_div);


_copyBtn.addEventListener('click', ()=> {
  selectCopyText(_copyBtn.value);
});
_copyBtn2.addEventListener('click', ()=> {
  selectCopyText(_copyBtn2.value);
});

使用示例:

虽然“复制到剪贴板”是最普遍需要的 JavaScript 功能之一,但还值得注意的是,所需的文本内容同样可能包含在表单元素中,例如 -