在我们的项目中,我们一直在使用一种功能,当我们选择一些文本并右键单击它时,文本被复制,另一次右键单击将导致复制的文本被粘贴到javascript中。代码工作正常,直到IE11。在IE11中我们得到错误
textEl.caretPos = document.selection.createRange().duplicate();
我已经研究了很多,发现IE11上不再支持document.selection,我们需要使用window.getSelection(),但这也没有用。我尝试了所有组合window.getSelection(); window.document.getSelection(); document.getSelection(); window.external.menuArguments.document.getSelection();
没有任何作用。我已经提到了这些链接
Unable to get property 'createRange' of undefined or null reference
https://tracker.phpbb.com/browse/PHPBB3-12094
这些dint可以帮助他们在任何地方要求使用window.getSelection()。
这是我的代码: 修改
请注意下面的代码在IE7 / 8和Chrome中运行正常,因为window.getSelection().toString()
为空,它在IE11上无效。如果这会产生任何差异,请在Iframe内部注意这一点。
/**
* Copies or Pastes text into a text box. If the
* text is selected, then right clicking on it does a copy.
* If no text is selected, then right clicking invokes a paste
* of any clipboard text into the textbox.
*
* NOTE: Pasting will replace any value already in the textbox
*/
function copyPasteHelper()
{
// if something is currently selected, copy it
var selectedText = "";
if(document.selection != null){// for IE 8 and below only
storeCaret (event.srcElement);
selectedText = document.selection.createRange().text;
}else if(typeof window.getSelection() != "undefined") // for IE 9+ and Chrome
{
//storeCaret (event.srcElement);
selectedText = window.getSelection().toString();
alert(selectedText);//this is empty
}
if (selectedText != "")
{
if(window.clipboardData)
{
window.clipboardData.setData("Text", selectedText);
var lefter2 = event.offsetY+0;
var topper2 = event.offsetX+15;
// oCopiedPopup.show(topper2, lefter2, 80, 23, window.event.srcElement);
}
else
{
jQuery("#clipboard", window.parent.document).val(selectedText);
}
}
else // if nothing is selected, paste whatever text is in the clipboard
{
pasteHelper();
}
}
任何帮助都将在此之前提前感谢。
答案 0 :(得分:2)
如果它对任何人都有帮助。我正在努力解决这个问题,最后发现这是因为我试图在无效的上下文中使用window.getSelection()。它不会在输入中返回选定的文本:text或textarea。相反,我必须使用selectionStart和selectionEnd,并从input元素中提取值并从那里解析所选文本。感谢http://help.dottoro.com/ljcvonpc.php获取此信息。