Any way to prevent “deselection” of highlighted text?

前端 未结 6 916
南旧
南旧 2020-12-10 13:54

Highlight some text on this webpage, then click basically anywhere on the document. Your selection will disappear.

Is there a way to prevent this behavior when the

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-10 14:22

    the best way that I figured out how to do this is, for IE you need to setup a listener on 'onselectstart'. For Mozilla and other browsers you can do on 'mousedown'. This will only work, if you don't use 'mousedown' in any other portion of your site!

    Snippet: YUI way: FF browser:

    • YAHOO.util.Event.addListener(window, 'mousedown', function(evt) { YAHOO.util.Event.preventDefault(evt); });

      IE Browser: In IE you are not allowed to set this listener on window, since in IE it doesn't work. best thing to do is on your body element set a class element, then reference it, and apply the listener to that element object.

    • // Get the element by class and assign to var bar YAHOO.util.Event.addListener(bar, 'selectstart', function(evt) { YAHOO.util.Event.preventDefault(evt); });

    if you want to do it the easy way, just do

    • window.onMouseDown = function() {return false;}

    or for IE

    • body.onSelectStart = function() {return false;}

    Hope this helps.

提交回复
热议问题