有時候,我們需要獲取滑鼠選中的文本部分,可以利用 window 的 selection 物件做到,
利用 window.getSelection() 可以得到 window 的 selection 物件,
HTML 部分:
<div id="box">
測驗文字測驗文字測驗文字測驗文字測驗文字測驗文字測驗文字測驗文字測驗文字
</div>
當選中文本的時候,最侄訓鼠會松開(mouseup),所以,需要用到 mouseup 事件,
JavaScript 部分:
let box = document.getElementById("box");
box.addEventListener("mouseup",function(){
let selectedText = window.getSelection().toString(); // 把選中的內容轉為字串,
if( selectedText.trim() !== ""){ // 去掉字符兩邊的空白
console.info( selectedText );
}
});
當然,也可以禁止用戶選擇任何內容,
let box = document.getElementById("box");
box.addEventListener("mouseup",function(){
window.getSelection().removeAllRanges(); // 去掉所有選中范圍,也就是禁止選擇內容
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/253499.html
標籤:其他
