【问题标题】:why document.execCommand('copy') doesnt copy here?为什么 document.execCommand('copy') 不在这里复制?
【发布时间】:2021-06-16 00:12:14
【问题描述】:

有一个列表,当我搜索它打开的颜色时,我想在单击列表项时复制颜色名称,颜色名称在 input[type=hidden] 中,但我无法复制输入。 execCommand('copy') 与 input[type=hidden] 配合良好。

链接到 codepen 但你不会得到列表,因为我使用 ajax 来获取颜色。 对不起,如果代码很乱,我正在学习!

codepen

    function copy(event) {
    var alertColorBox = document.querySelector('.alertCopy .color');
    alertColorBox.style.backgroundColor = event.target.style.backgroundColor;
    var alert = document.querySelector('.alertCopy');
    alert.classList.remove('alertAnimation');
    var alert_span = document.querySelector('.alertCopy span');
    // my question code part
    var input = event.target.querySelector('input');
    input.select();
    document.execCommand('copy');
    // my question code part
    alert_span.innerHTML = input.value;
    alert.classList.add('alertAnimation');
    setTimeout(removeAlert, 5000);
}

【问题讨论】:

    标签: javascript


    【解决方案1】:

    前段时间我也遇到过同样的问题。您的代码可能适用于 Firefox,但不适用于 Chromium。

    我要做的是删除输入的 type="hidden",然后我给了 position="absolute" 和 "top: -1000px";

    这不是最好的方法,但可以。输入将不再可见(在屏幕上),但浏览器将复制内容。

    我做了这个类来简化:

    .inputToHide {
      opacity: 0;
      padding: 0;
      margin: 0;
      position: absolute;
      top: -1000px;
    }
    

    Ps.:尽量缩进你的代码以便于理解

    ================================================ =========== 编辑

    如果你可以控制你的 HTML,在你的 div 中设置一个包含颜色名称的数据颜色,然后在函数中你只需要创建一个输入,附加到正文中然后复制内容,就像这样:

    var colorInput = document.createElement('input');
    colorInput = colorName.getAttribute('data-color');
                    
    document.body.appendChild(colorInput);
    colorInput.select();
    document.execCommand("copy");
    
    document.body.removeChild(colorInput);
    

    毕竟这是一个更好的选择

    【讨论】:

      猜你喜欢
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-22
      相关资源
      最近更新 更多