JS----复制事件(文字选取)

<html>

<head>
    <meta charset="utf-8">
    <title>JS----复制事件(文字选取)</title>
    <meta name="keyword" content="JS----获取选中文本">
    <meta name="discription" content="JS----获取选中文本">
</head>

<body>
<p>复制:1234567890</p>
<script>
funcSelect(document, showResult);
function funcSelect(w, fn) {
    w.oncopy = 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 showResult(txt, tar) {
	var dm = document.domain;
	var url = window.location.href;
    console.log(dm+","+url+"," + tar.tagName + "," + txt);
}
</script>
</body>
</html>
posted @ 2018-04-26 17:30  SunLike阿理旺旺  阅读(353)  评论(0编辑  收藏  举报