![](/img/trans.png)
[英]How do I wrap a text selection from window.getSelection().getRangeAt(0) with an html tag?
[英]how to i assign text direction RTL for window.getSelection value, I tried but how to remove getSelection from existing value of text area
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>
獲取文本位置。 但是此答案提供了一種從<div>
獲取文本位置的方法。 您可以使<div>
看起來像<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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.