gpt4 book ai didi

javascript - 我如何为 window.getSelection 值分配文本方向 RTL,我试过了但是如何从文本区域的现有值中删除 getSelection

转载 作者:行者123 更新时间:2023-11-28 01:30:50 27 4
gpt4 key购买 nike

var F1 = document.getElementById('samuText').value;

function insertAtCursor()
{
if (window.getSelection)
{
sel = window.getSelection();
document.getElementById('samuText').value = F1+sel // here i need to remove selected value from F1
//alert(sel);
//ocument.getElementById(sel).style.direction = "rtl";

}
}
<textarea id="samuText">Samudrala Ramu</textarea><button onclick="insertAtCursor();">RLM</button>

最佳答案

好的,您应该能够获取所选文本及其索引(文本位置)。我搜索但没有找到任何解决方案来从 <textarea> 获取文本位置.但是this answer提供了一种从 <div> 获取文本位置的方法.你可以 make <div> look like <textarea> .我结合了这两个答案并稍作修改。注意 changeValue函数是操作文本的关键。

<html>
<style>
#main {
-moz-appearance: textfield-multiline;
-webkit-appearance: textarea;
border: 1px solid gray;
font: medium -moz-fixed;
font: -webkit-small-control;
height: 28px;
overflow: auto;
padding: 2px;
resize: both;
width: 400px;
}
</style>

<body>
<div id="main" contenteditable>Samudrala RamuSamu</div>
<input type="button" onclick="changeValue()" unselectable="on" value="Get selection">
</body>

<script>
function getSelectionCharOffsetsWithin(element) {
var start = 0, end = 0;
var sel, range, priorRange;
if (typeof window.getSelection != "undefined") {
range = window.getSelection().getRangeAt(0);
priorRange = range.cloneRange();
priorRange.selectNodeContents(element);
priorRange.setEnd(range.startContainer, range.startOffset);
start = priorRange.toString().length;
end = start + range.toString().length;
} else if (typeof document.selection != "undefined" &&
(sel = document.selection).type != "Control") {
range = sel.createRange();
priorRange = document.body.createTextRange();
priorRange.moveToElementText(element);
priorRange.setEndPoint("EndToStart", range);
start = priorRange.text.length;
end = start + range.text.length;
}
return {
start: start,
end: end,
value: range.toString()
};
}

function changeValue() {
var mainDiv = document.getElementById("main");
var sel = getSelectionCharOffsetsWithin(mainDiv);

var mainValue = mainDiv.textContent;
var newValue = mainValue.slice(0,sel.start) + mainValue.slice(sel.end) + sel.value;
mainDiv.textContent = newValue;
}
</script>

</html>

关于javascript - 我如何为 window.getSelection 值分配文本方向 RTL,我试过了但是如何从文本区域的现有值中删除 getSelection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50981148/

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