最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I cancel a text selection after the initial mousedown event? - Stack Overflow

programmeradmin3浏览0评论

I'm trying to implement a pop-up menu based on a click-and-hold, positioned so that a (really) slow click will still trigger the default action, and with the delay set so that a text-selection gesture won't usually trigger the menu.

What I can't seem to do is cancel the text-selection in a way that doesn't prevent text-selection in the first place: returning false from the event handler (or calling $(this).preventDefault()) prevents the user from selecting at all, and the obvious $().trigger('mouseup') doesn't doesn't do anything with the selection at all.

  • This is in the general context of a page, not particular to a textarea or other text field.
  • e.stopPropogation() doesn't cancel text-selection.
  • I'm not looking to prevent text selections, but rather to veto them after some short period of time, if certain conditions are met.

I'm trying to implement a pop-up menu based on a click-and-hold, positioned so that a (really) slow click will still trigger the default action, and with the delay set so that a text-selection gesture won't usually trigger the menu.

What I can't seem to do is cancel the text-selection in a way that doesn't prevent text-selection in the first place: returning false from the event handler (or calling $(this).preventDefault()) prevents the user from selecting at all, and the obvious $().trigger('mouseup') doesn't doesn't do anything with the selection at all.

  • This is in the general context of a page, not particular to a textarea or other text field.
  • e.stopPropogation() doesn't cancel text-selection.
  • I'm not looking to prevent text selections, but rather to veto them after some short period of time, if certain conditions are met.
Share Improve this question edited Sep 23, 2008 at 2:52 asked Sep 22, 2008 at 8:10 cwillu-gmailcwillu-gmail
Add a ment  | 

6 Answers 6

Reset to default 5

Try this:

var input = document.getElementById('myInputField');
if (input) {
    input.onmousedown = function(e) {

        if (!e) e = window.event;
        e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();

    }
}

And if not, have a read of:

http://www.quirksmode/js/introevents.html

In addition to the top thread, there is an official way to implement what I think you want in DOM. What you can use in lieu of events is something called a range object.

Consider, (which works definitively on FF3)

window.onclick = function(evt)
{
   // retrieves the selection and displays its content
   var selectObj = window.getSelection();
   alert(selectObj);

   // now collapse the selection to the initial point of the selection
   var rangeObj = selectObj.getRangeAt(0);
   rangeObj.collapse(true);
}

Unfortunately, this doesn't quite fly with IE, Opera, Chrome, or Safari; not sure why, because in Opera, Chrome, or Safari, there is something associated with the collapse and getRangeAt methods. If I know more, I'll let you know.


An update on my previous answer, one that works more universally is the selection object and collapse, collapseToStart, collapseToEnd methods. (link text)

Now consider the 2.0 of the above:


window.onmouseup = function(evt)
{
   var selectObj = window.getSelection();
   alert(selectObj); // to get a flavor of what you selected

   // works in FF3, Safari, Opera, and Chrome
   selectObj.collapseToStart();

   // works in FF3, Safari, Chrome (but not opera)
   /* selectObj.collapse(document.body, 0); */

   // and as the code is native, I have no idea why...
   // ...and it makes me sad
}

I'm not sure if this will help, exactly, but here is some code to de-select text:

// onselectstart is IE-only
if ('undefined' !== typeof this.onselectstart) {
    this.onselectstart = function () { return false; };
} else {
    this.onmousedown   = function () { return false; };
    this.onclick       = function () { return true;  };
}

"this" in this context would be the element for which you want to prevent text selections.

An answer to this question works for me: How to disable text selection using jquery?

(It not only disables, but also cancels, any text selection.
At least on my puter in FF and Chrome.)

Here is what the answer does:

    .attr('unselectable', 'on')

    '-ms-user-select': 'none',
    '-moz-user-select': 'none',
    '-webkit-user-select': 'none',
    'user-select': 'none'

    .each(function() {  // for IE
      this.onselectstart = function() { return false; };
    });

$(this).focus() (or anything along the lines of document.body.focus()) seems to do the trick, although I haven't tested it much beyond ff3.

Thanks to knight for the beginnings of a universal solution. This slight modification also includes support for IE 7-10 (and probably 6).

I had a similar prob as cwillu-gmail.. needed to attach to the shift-click event (click on label while holding shift key) to perform some alternate functionality when in a specific "design" mode. (Yeah, sounds weird, but it's what the client wanted.) That part was easy, but had the annoying effect of selecting text. This worked for me: (I used onclick but you could use onmouseup.. depends on what you are trying to do and when)

var element = document.getElementById("myElementId");
element.onclick = function (event)
{
    // if (event.shiftKey) // unment this line to only deselect text when clicking while holding shift key
    {
        if (document.selection)
        {
            document.selection.empty(); // works in IE (7/8/9/10)
        }
        else if (window.getSelection)
        {
            window.getSelection().collapseToStart(); // works in chrome/safari/opera/FF
        }
    }
}
发布评论

评论列表(0)

  1. 暂无评论