gpt4 book ai didi

javascript - window.getSelection 在textarea中获取正确的选择

转载 作者:行者123 更新时间:2023-12-04 13:02:06 37 4
gpt4 key购买 nike

在firefox和chrome中window.getSelection用于获取document中的当前选择,但是如果当前选择在textarea中,window.getSelection返回的不是选择,而是textarea本身。那么,如何在firefox和chrome中正确选择呢?

最佳答案

您是否需要在文本区域中获取选定的文本?您可能会要求 selectionStart 和 selectionEnd(在 Internet Explorer 中不存在,适用于 Firefox 和 Chrome)

 Select some text below and then click the button:<br/>
<textarea id="myTextarea" rows="5" cols="30">
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
</textarea>
<button onclick="alert(getTextSelection())">alert text selection</button>

<script type="text/javascript">
function getTextSelection(){
var field = document.getElementById("myTextarea");
var startPos = field.selectionStart;
var endPos = field.selectionEnd;
var field_value = field.value;
var selectedText = field_value.substring(startPos,endPos);
return selectedText;
}
</script>

如果有多个文本区域并且您希望在选择时获得输出:

Select some text in either textarea:<br/> 
<textarea rows="5" cols="30" onselect="alert(getTextSelection(this))">
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
</textarea>


<textarea rows="5" cols="30" onselect="alert(getTextSelection(this))">
fate it seems
not without a sense of irony
</textarea>


<script type="text/javascript">
function getTextSelection(field){
var startPos = field.selectionStart;
var endPos = field.selectionEnd;
var selectedText = field.value.substring(startPos,endPos);
return selectedText;
}
</script>

或者你仍然可以使用一个按钮来完成它,但是使用一个全局变量:

Select some text in either textarea and click the button:<br/> 
<textarea rows="5" cols="30" onselect="window.selectedTextarea=this">
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
</textarea>


<textarea rows="5" cols="30" onselect="window.selectedTextarea=this">
fate it seems
not without a sense of irony
</textarea>



<button onclick="alert(getTextSelection())">alert text selection</button>



<script type="text/javascript">
// warning: global variable: dirty!!!
var selectedTextarea

function getTextSelection(){
var field = window.selectedTextarea;
var startPos = field.selectionStart;
var endPos = field.selectionEnd;
var selectedText = field.value.substring(startPos,endPos);
return selectedText;
}
</script>

关于javascript - window.getSelection 在textarea中获取正确的选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10596606/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com