有contenteditable属性的容器,单击后选中全部文本,然后编辑

怎样实现单击后选中全部文本?

阅读 5.4k
评论
    3 个回答
    • 250

    stackoverflow找到了解决的办法,selectNodeContents对具有contenteditable='true'的容器有效

        <div contenteditable='true' id="selectable" onclick="selectText('selectable')">http://example.com/page.htm</div>
        
        <script type="text/javascript">
            function selectText(containerid) {
                if (document.selection) {
                    var range = document.body.createTextRange();
                    range.moveToElementText(document.getElementById(containerid));
                    range.select();
                } else if (window.getSelection) {
                    var range = document.createRange();
                    range.selectNodeContents(document.getElementById(containerid));
                    window.getSelection().removeAllRanges();
                    window.getSelection().addRange(range);
                }
            }
        </script>