编程语言
首页 > 编程语言> > javascript – 有没有办法在Chrome和/或IE中用JS选择MULTIPLE文本区域?

javascript – 有没有办法在Chrome和/或IE中用JS选择MULTIPLE文本区域?

作者:互联网

Firefox 3可以使用JS选择MULTIPLE文本区域.
有没有办法在Chrome和IE中这样做?

我真的试图找到一种选择多重方式的方法
Chrome和IE9网页中的textareas.

信息:
http://help.dottoro.com/ljxsqnoi.php

示例:
http://jsfiddle.net/t3sWz/

代码FireFox3.5只…(但这是问题):

<html>

<head>
    <meta charset="UTF-8">
    <style>
        #trigger { background: yellow }
    </style>
</head>

<body>
    <p id="test">
        This is some text you can highlight by dragging or clicking below.
    </p>
    <span id="trigger">
        Click here to select "This" and "some"
    </span>
    <a> - Firefox only :-(</a>
    <br>
    <br>
    <br>
    <br>
    <br>
    <input type="button" value="Get selection" onm ousedown="getSelText()">
    <form name=aform>
        <textarea name="selectedtext" rows="5" cols="20">
        </textarea>
    </form>
    <script>
        var testCase = function() {
            var userSelection;

            if (window.getSelection) {
                userSelection = window.getSelection();
            } // No support for IE
            var textNode = document.getElementById('test').firstChild;
            var theRange = document.createRange();

            // select 0th–4th character
            theRange.setStart(textNode, 0);
            theRange.setEnd(textNode, 4);

            // set user selection    
            userSelection.addRange(theRange);

            var textNode = document.getElementById('test').firstChild;
            var theRange = document.createRange();

            // select 8th–12th character
            theRange.setStart(textNode, 8);
            theRange.setEnd(textNode, 12);

            // set user selection    
            userSelection.addRange(theRange);
        };

        window.onload = function() {
            var el = document.getElementById('trigger');
            el.onclick = testCase;
        };

        function getSelText() {
            var txt = '';
            if (window.getSelection) {
                txt = window.getSelection();
            } else if (document.getSelection) {
                txt = document.getSelection();
            } else if (document.selection) {
                txt = document.selection.createRange().text;
            } else
            return;
            document.aform.selectedtext.value = txt;
        }
    </script>
</body>

解决方法:

在主要浏览器中,只有Firefox支持用户选择中的多个范围.其他浏览器(WebKit,Opera,IE9)确实有Selection API来支持多个范围,但目前不支持它. WebKit是apparently not planning to add support any time soon.至于Opera和IE,我不知道.

标签:javascript,range,firefox,textnode,textrange
来源: https://codeday.me/bug/20190626/1297223.html