获取盒子中选中的文字

复制代码
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<div><p onmouseup="mytest()">只是一段文本其余的还有很多的文字</p></div>
<script>

    function mytest(e){
        console.log(window.getSelection);
        var txt = window.getSelection?window.getSelection():document.selection.createRange().text;
        if(txt==""){//当选中内容为空时,阻止事件发生
            window.event? window.event.cancelBubble = true : e.stopPropagation();
        }else{
            var txt1=String.toString(txt);//得到的选中的文本是一个对象,需要转化为字符串
            alert(txt1);
        }
    }

</script>
</body>
</html>
复制代码

 

posted on   马玉豪  阅读(8)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示