JavaScript 练手小技巧:JS 获取选中的文本或者禁止选择文本

有时候,我们需要获取鼠标选中的文本部分,可以利用 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();  // 去掉所有选中范围,也就是禁止选择内容
});

猜你喜欢

转载自blog.csdn.net/weixin_42703239/article/details/113204923