首页 > 解决方案 > 单击按钮以选择输入中的文本不起作用

问题描述

在js中没有选择文本尝试了所有方法。select()并且btn.select()没有选择文本框中的文本

        var in = document.getElementById("in");
        var btn = document.getElementById("btn");
    
        btn.onclick() = function(){
            in.focus();
            in.select();
            in.setSelectionRange(0,9999);
             document.execCommand("copy");
        };
    <body>
        <input id="in" type="text">
        <button id="btn" >Copy </button>
    </body>

标签: javascript

解决方案


in是 javascript 中的保留键,因此不能使用它,()当您想将其分配给值时,您必须在 onclick 后删除。

            var inputField = document.getElementById("in");
            var btn = document.getElementById("btn");
        
            btn.onclick = function(){
                inputField.focus();
                inputField.select();

                inputField.setSelectionRange(0, 99999)
                document.execCommand("copy");
            };
            
            var linkTag = document.getElementById("link");
            var btnLink = document.getElementById("btn-link");

        btnLink .onclick = function(){
            const range = document.createRange();
            range.selectNode(linkTag );
            const selection = window.getSelection();
            selection.removeAllRanges();
            selection.addRange(range);

            document.execCommand('copy');
        };
        <body>
            <div>
                <input id="in" type="text">
                 <button id="btn" >Copy </button>
             </div>
            <div>
                 <a href="google.com" id="link">google.com</a>
                 <button id="btn-link" >Copy </button>
             </div>
        </body>


推荐阅读