JS----获取选中文本

<html>

<head>
    <meta charset="utf-8">
    <title>JS----获取选中文本</title>
    <meta name="keyword" content="JS----获取选中文本">
    <meta name="discription" content="JS----获取选中文本">
</head>

<body>
<p>423432432432423</p>


<script>
select(document, cbFunc);

function select(w, fn) { w.onmouseup = function(e) {
        var event = window.event || e;
        var target = event.srcElement ? event.srcElement : event.target;
        if (/input|textarea/i.test(target.tagName) && /firefox/i.test(navigator.userAgent)) {
            //Firefox在文本框内选择文字 
            var staIndex = target.selectionStart;
            var endIndex = target.selectionEnd;
            if (staIndex != endIndex) {
                var sText = target.value.substring(staIndex, endIndex);
                fn(sText, target);
            }
        } else {
            //获取选中文字 
            var sText = document.selection == undefined ? document.getSelection().toString() : document.selection.createRange().text;
            if (sText != "") {
                //将参数传入回调函数fn 
                fn(sText, target);
            }
        }
    }
}

function cbFunc(txt, tar) {
	var dm = document.domain;
	var url = window.location.href;
    alert(dm+","+url+"," + tar.tagName + "," + txt);
}
</script>
</body>
</html>

  

posted @ 2018-04-17 10:07  SunLike阿理旺旺  阅读(236)  评论(0编辑  收藏  举报