我想替换当前选定的范围文本,用HTML标记包装HTML并重新渲染。
HTML
<div ng-mouseup="mouseUpEvent()">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus aliquam sodales ipsum quis tincidunt. In scelerisque lorem a metus volutpat volutpat.
</div>
JS
//Get Selected Content
$scope.mouseUpEvent = function() {
// Get the user selected content and store in a var
$scope.selectedText = $scope.getSelectionText();
//need a function to return the selected content but wrapped with <b></b>
};
//Get selection range
$scope.getSelectionText = function(){
var userSelectedText = "";
if (window.getSelection) {
userSelectedText = window.getSelection().toString();
$scope.myselectText = window.getSelection().toString();
$scope.myselectText.replace ($scope.myselectText, 'yellow');
} else if (document.selection && document.selection.type != "Control") {
userSelectedText = document.selection.createRange().text;
}
return userSelectedText;
}
答案 0 :(得分:2)
这是一个非常简单的问题解决方案(使用纯香草js)
您可以通过两种方式向对象添加事件侦听器。
通过将侦听器添加到HTML中的对象
<div id="myButton" onMouseUp="doSomething()"></div>
或来自JavaScript
document.getElementById("myButton").addEventListener("mouseup", function(){
//Do something when the mouse Up event happens.
});
如果您希望JavaScript在页面加载时自动添加eventListeners,那么您可以使用此
window.onload = function(){
document.getElementById("myButton").addEventListener("mouseup", function(){ DO SOMETHING CODE HERE; });
};
解决您的问题
HTML
<div id="SampleText" onMouseUp="captureText()">Please select this text</div>
的JavaScript
function captureText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type !== "Control") {
text = document.selection.createRange().text;
}
return text;
//or pass text to a function for it to be used useText(text);
}//End function
更新:
如果您想从整个页面捕获所选文本,则需要将整个页面包装在包装器中,并将evenListener添加到包装器中。
<div id="PageWrapper" onMouseUp="captureText()">
//All Page content goes here
</div><!-- End PageWrapper -->
答案 1 :(得分:0)
对于Angular,你有 ng-mouseup 这是一个关于你如何做角度
的例子<强> HTML 强>
<div ng-mouseup="getSelectedText()">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer hendrerit lacus gravida augue mattis, quis auctor ex pulvinar.
</div>
<div ng-bind="showSelections"></div>
<强> SCRIPT 强>
function myCtrl($scope){
$scope.getSelectedText = function(){
$scope.showSelection = $scope.getSelectionText();
};
$scope.getSelectionText = function() {
var selectedText = "";
if (window.getSelection) {
selectedText = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
selectedText = document.selection.createRange().text;
}
return selectedText;
};
}