Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/423.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在Google Chrome和Internet Explorer中删除文本区域中的选定文本_Javascript - Fatal编程技术网

Javascript 在Google Chrome和Internet Explorer中删除文本区域中的选定文本

Javascript 在Google Chrome和Internet Explorer中删除文本区域中的选定文本,javascript,Javascript,我可以在internet explorer中使用以下代码获取所选文本: var selectedText; // IE version if (document.selection != undefined) { textComponent.focus(); var sel = document.selection.createRange(); selectedText = sel.text; } 但是,如何删除TEXTAREA中选定的文本,例如,在Go

我可以在internet explorer中使用以下代码获取所选文本:

var selectedText;
  // IE version
  if (document.selection != undefined)
  {
    textComponent.focus();
    var sel = document.selection.createRange();
    selectedText = sel.text;
  }

但是,如何删除TEXTAREA中选定的文本,例如,在Google Chrome和Internet Explorer中使用JavaScript?

如果您使用的是IE v9或更高版本,请使用适用于所有现代浏览器的
window.getSelection()

您可能需要稍微调整一下索引,但是下面的代码应该或多或少能起作用

var originalText = document.getElementById("yourTextAreaId").value;
var selectedText = window.getSelection();
var startIndex = originalText.indexOf(selectedText) + 1;
var endIndex = startIndex + selectedText.length; 
var newText = originalText.substring(0,startIndex) + orignalText.substring(endIndex);
document.getElementById("yourTextAreaId").value = newText 

用户2793390给出的答案并不完全正确! 如果所选文本不是整个文本中第一个出现的文本,则不起作用

我有一个类似的问题,我使用了另一种方法

var selectedElemnt = document.getElementById("yourTextAreaId");
var selectedText = selectedElemnt.value;
var newText = selectedText.substr(0, selectedElemnt.selectionStart) + selectedText.substr(selectedElemnt.selectionEnd);
selectedElemnt.value = newText;

如果所选文本不止一次出现,而不是第一次出现,该怎么办?