无法使用 JavaScript 从文本框中获取所选文本?适用于火狐浏览器,而不是IE

Unable to get the selected text from a Text Box Using JavaScript ? Works in Firefox and not in IE?

本文关键字:文本 火狐浏览器 适用于 IE 获取 JavaScript      更新时间:2023-09-26

我正在尝试选择在"文本"框中选择的特定文本。它在Firefox中工作正常,在IE中不起作用。

我的代码是 ,

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<HTML>
<HEAD><TITLE>Selection</TITLE>
<SCRIPT type="text/javascript">
function displayText()
{
  var text = document.getElementById("text");
  var t = text.value.substr(text.selectionStart,text.selectionEnd-text.selectionStart);
  alert(t);
}
</SCRIPT>
</HEAD>
<BODY>
<input type="text" id="text"/>
 
<INPUT type="button" onclick="displayText()" value="Select text and click here" />
</BODY>
</HTML>

请给出您的建议。我的代码中是否缺少任何内容?

在 ie,它是

document.selection.createRange().htmlText;

尝试更新的功能:

function displayText()
{
  var text = document.getElementById("text");
  var t;
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    t = document.selection.createRange().htmlText;
  } else {
    t = text.value.substr(text.selectionStart,text.selectionEnd-text.selectionStart)
  }
  alert(t);
}