展示鼠标划取得数据

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

FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic supportYesYes                 9(Yes)(Yes)

 Mobile

FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support?????

PS:以上内容仅供参考,如有疑问敬请指正。

转载于:https://my.oschina.net/ochmdlc/blog/1585755

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值