获取盒子中选中的文字

<!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 2022-09-20 14:11  马玉豪  阅读(14)  评论(0)    收藏  举报

导航