[英]Displaying highlighted text in textarea
I have implemented a code that when i highlight a word or phrase it is added in the textarea but as soon as I click on the mouse the highlighted text value goes from the textarea. 我实现了一个代码,当我突出显示一个单词或短语时,它会添加到文本区域中,但是当我单击鼠标时,突出显示的文本值就会从文本区域中消失。
I am implementing this using Angularjs. 我正在使用Angularjs实现这一点。
This is my HTML & Angularjs code:
<div ng-app="myApp" ng-controller="caseCtrl">
<form name="aform" >
<textarea id="sel" rows="5" cols="20"></textarea>
</form>
<div>
<p>highlight the text to paste it in textbox.</p>
</div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('caseCtrl', function($scope) {
function getSelectionText() {
var text = "";
if ((activeElTagName == "textarea")) {
} else if (window.getSelection) {
text = window.getSelection().toString();
}
return text;
}
document.onclick = function() {
document.getElementById("sel").value = getSelection();
};
});
</script>
when i highlight the text it is pasted in textbox but when i click on the mouse the text gets disappeared from textbox. 当我突出显示文本时,它将粘贴在文本框中,但是当我单击鼠标时,文本将从文本框中消失。 Suggest me what to do ?
建议我怎么办?
In your case when you click somewhere, the selected text no longer exists, so text
value gets updated to ""
a blank string. 对于您而言,当您单击某个位置时,所选文本不再存在,因此
text
值将更新为""
空白字符串。 You will have to put a check for that. 您将必须为此检查。
Your function should look like: Edited: 您的函数应如下所示 :
var text2 = "";
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
console.log(text.length);
if(text.length!=0) {
text2 =text;
}
}
return text2;
}
document.addEventListener("click", function() {
document.getElementById("sel").value = getSelectionText();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.