Range对象和Selection对象

Range可以用 Document 对象的 createRange方法创建,也可以用Selection对象的getRangeAt方法取得;可以通过构造函数 Range() 来获得一个 Range

接口文档链接

https://developer.mozilla.org/zh-CN/docs/Web/API/Range
https://developer.mozilla.org/zh-CN/docs/Web/API/Selection

附一段ract-copy-to-clipboard关键源码(一键复制)

//需要判断操作系统,并调取对应复制快捷键
function format(message) {
    var copyKey = (/mac os x/i.test(navigator.userAgent) ? '⌘' : 'Ctrl') +     '+C';
    return message.replace(/#{\s*key\s*}/g, copyKey);
}
//粘贴调用函数参数text:需要粘贴的内容;options:其他参数
function copy(text, options) {
    var debug, message, reselectPrevious, range, selection, mark, success = false;
    if (!options) { options = {}; }
    debug = options.debug || false;
  try {
     //如果是常规浏览器做第一次尝试

     //对document.activeElement元素做处理的函数;本文没有做说明
     reselectPrevious = deselectCurrent();
     //创建一个range对象
     range = document.createRange();
     //获取一个range对象
     selection = document.getSelection();

     //创建一个元素,存放需要复制的内容并设置该元素的样式
     mark = document.createElement('span');
     mark.textContent = text;
     //reset user styles for span element
     mark.style.all = 'unset';
     //prevents scrolling to the end of the page
     mark.style.position = 'fixed';
     mark.style.top = 0;
     mark.style.clip = 'rect(0, 0, 0, 0)';
     //used to preserve spaces and line breaks
     mark.style.whiteSpace = 'pre';
     //do not inherit user-select (it may be `none`)
     mark.style.webkitUserSelect = 'text';
     mark.style.MozUserSelect = 'text';
     mark.style.msUserSelect = 'text';
     mark.style.userSelect = 'text';
     //将创建的元素放到页面中
     document.body.appendChild(mark);
     
     //设定一个包含节点和节点内容的 Range 
     range.selectNode(mark);
     //一个区域对象将被加入选区
     selection.addRange(range);
    
     //运行命令来操纵可编辑区域的内容
     var successful = document.execCommand('copy');
     if (!successful) {
            throw new Error('copy command was unsuccessful');
     }
     success = true;

} catch (err) {
     debug && console.error('unable to copy using execCommand: ', err);
     debug && console.warn('trying IE specific stuff');
     try {
           //如果是ie浏览器支持clipboardData属性;做第二次尝试
            window.clipboardData.setData('text', text);
            success = true;
     } catch (err) {
            debug && console.error('unable to copy using clipboardData: ', err);
            debug && console.error('falling back to prompt');
            message = format('message' in options ? options.message : defaultMessage);
            window.prompt(message, text);
     }
} finally {
     //尝试结束最后将selection对象和range对象添加的元素移出
     if (selection) {
            if (typeof selection.removeRange == 'function') {
                   selection.removeRange(range);
            } else {
                   selection.removeAllRanges();
            }
     }
     //尝试结束最后将mark元素移出
     if (mark) {
            document.body.removeChild(mark);
     }
    reselectPrevious();
}
//返回是否复制成功
 return success;
}

你可能感兴趣的:(Range对象和Selection对象)