Window.getSelection
一.返回一个 selection 对象,表示用户选择的文本范围或光标的当前位置
const selection = window.getSelection() ;
selection是一个selection对象。 如果想要将 election转换为字符串,可通过连接一个空字符串("")或使用 String.toString()
方法。
栗子如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript" src="js/jquery-2.1.0.js"></script>
</head>
<body>
<div id="content" style="background: orange">
世有伯乐,然后有千里马。千里马常有,而伯乐不常有。故虽有名马,祇辱于奴隶人之手,骈死于槽枥之间,不以千里称也。马之千里者,一食或尽粟一石。食马者不知其能千里而食也。是马也,虽有千里之能,食不饱,力不足,才美不外见,且欲与常马等不可得,安求其能千也?策之不以其道,食之不能尽其材,鸣之而不能通其意,执策而临之,曰:“天下无马!”呜呼!其真无马邪?其真不知马也!
</div>
</body>
<script type="text/javascript">
$(function(){
$("#content").mouseup(function(e){
if(window.getSelection) {
var textObj = document.getElementById("content");
var selectedText = window.getSelection().toString();
alert(selectedText);
selectedText = "<span style='background:violet'>"+selectedText+"</span>";
var start = window.getSelection().anchorOffset;
var end = window.getSelection().focusOffset;
console.log(start+"\n"+end)
var tempStr1 = textObj.innerHTML.substring(0,start);
var tempStr2 = textObj.innerHTML.substring(end);
document.getElementById("content").innerHTML = tempStr1 + selectedText + tempStr2 ;
}
});
});
</script>
</html>
获取鼠标划取得内容
二.浏览器兼容性
Desktop
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | Yes | Yes | 9 | (Yes) | (Yes) |
Mobile
Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
Basic support | ? | ? | ? | ? | ? |
PS:以上内容仅供参考,如有疑问敬请指正。