开发者

How to disable text selection via jQuery?

I know this question have been already asked开发者_如何学Python (here), but all the answers I've found dealt with css selector :selection (that is not yet too widely supported by browsers).

So, how can I disable text selection on my html page via jQuery, not relying on css tricks?


Here is a simple one-liner to disable selecting text on your whole page. (whether you should or not is another question)

$(document).bind('selectstart dragstart', function(e) {
  e.preventDefault();
  return false;
});


If you want to avoid plugins, you can extract the relevant parts from the jQuery UI source:

/*!
 * jQuery UI 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI
 */
$.support.selectstart = "onselectstart" in document.createElement("div");
$.fn.disableSelection = function() {
    return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
        ".ui-disableSelection", function( event ) {
        event.preventDefault();
    });
};

$("#somediv").disableSelection();


Include jQuery UI and use $(element).disableSelection().

However, disabling text selection is very user-unfriendly unless used in a context where accidental selections are likely (e.g. Drag&Drop or buttons where users are likely to doubleclick to perform multiple changes faster (e.g. in spinners))


Try that http://code.jdempster.com/jQuery.DisableTextSelect/jquery.disable.text.select.js

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜