简体   繁体   中英

How to get selected text on click of an element in javascript

I have a div with [contenteditable=true] attribute. When I select some text and click a button, I want to get the selected text. I did the following:

$(".btn").click(function (){
   alert(window.getSelection());
});

The above code does not alert anything. If I change the .btn element to an img element, the alert outputs the selected text. What can I do to get selected text on click of any element

Thid is my html code:

<li class="btn">Selection </li>
<div contenteditable="true">Some text here</div>

When you select your required text and click the button, as Ramon & adeneo explains in his comment, the focus is lost. Button command is executed at mouseup at which point the selection is cleared. As far as I understand, the reason why your code works with an image because unlike a button the image command is executed at mousedown .

My suggestion would be to try an .on('mousedown', ...) command instead of a simple click command.

    <script language=javascript>
    function getSelText()  {
        var txt = '';
        if (window.getSelection) {
            txt = window.getSelection();
        }
        else if (document.getSelectiion) {
            txt = document.getSelection();
        }
        else if (document.selection) {
           txt = document.selection.createRange().text;
        }
        else return;
        alert(txt)
     }


      window.document.onmousedown = function() {
        getSelText()
     }
     </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM