首页 > 解决方案 > JS IE 错误(对象不支持属性或方法“选择”)

问题描述

试图将一些信息复制到剪贴板。

在 Chrome 和其他工作正常,在 IE 中我得到错误:“对象不支持属性或方法'select'”

html:

<textarea name="wtBodyInpt" id="wtBodyInpt">Copy This</textarea>

JS:

function copyBodyToClipboard (BodyInpt) {
   // Select text inside element
   BodyInpt.focus();
   BodyInpt.select();
   // Copy text to clipboard
   document.execCommand('copy');
}
copyBodyToClipboard(wtBodyInpt)

标签: javascriptinternet-explorer

解决方案


您需要通过使用其 ID 或名称访问元素来创建元素的对象。

例子:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">

</head>
<body>

<p>Try to paste the text by pressing ctrl + v in a different window, to see the effect.</p>


<textarea name="wtBodyInpt" id="wtBodyInpt">Copy This Text</textarea>

<p>The document.execCommand() method is not supported in IE8 and earlier.</p>

<script>
function copyBodyToClipboard (element) {
  var copyText = document.getElementById(element);
  copyText.select();
  copyText.setSelectionRange(0, 99999);
  document.execCommand("copy");
  
 
}
var str="wtBodyInpt";
copyBodyToClipboard (str)

</script>

</body>
</html>

在 IE 11 浏览器中输出:

在此处输入图像描述


推荐阅读