[英]Displaying highlighted text in textarea
我實現了一個代碼,當我突出顯示一個單詞或短語時,它會添加到文本區域中,但是當我單擊鼠標時,突出顯示的文本值就會從文本區域中消失。
我正在使用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>
當我突出顯示文本時,它將粘貼在文本框中,但是當我單擊鼠標時,文本將從文本框中消失。 建議我怎么辦?
對於您而言,當您單擊某個位置時,所選文本不再存在,因此text
值將更新為""
空白字符串。 您將必須為此檢查。
您的函數應如下所示 :
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.