Is there a way to make a DIV unselectable?

Here is an interesting CSS questions for you!

I have a textarea with a transparent background overlaying some TEXT that I'd like to use as a sort of watermark. The text is large and takes up a majority of the textarea. It looks nice, the problem is when the user clicks in the textarea it sometimes selects the watermark text instead. I want the watermark text to never be selectable. I was expecting if something was lower in the z-index it would not be selectable but browsers don't seem to care about z-index layers when selecting items. Is there a trick or way to make it so this DIV is never selectable?


I wrote a simple jQuery extension to disable selection some time back: Disabling Selection in jQuery . You can invoke it through $('.button').disableSelection();

Alternately, using CSS (cross-browser):

.button {
        user-select: none;
        -moz-user-select: none;
        -khtml-user-select: none;
        -webkit-user-select: none;
        -o-user-select: none;
} 

The following CSS code works almost modern browser:

.unselectable {
    -moz-user-select: -moz-none;
    -khtml-user-select: none;
    -webkit-user-select: none;
    -o-user-select: none;
    user-select: none;
}

For IE, you must use JS or insert attribute in html tag.

<div id="foo" unselectable="on" class="unselectable">...</div>

Just updating aleemb's original, much-upvoted answer with a couple of additions to the css.

We've been using the following combo:

.unselectable {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    -o-user-select: none;
    user-select: none;
}

We got the suggestion for adding the webkit-touch entry from:
http://phonegap-tips.com/articles/essential-phonegap-css-webkit-touch-callout.html

2015 Apr: Just updating my own answer with a variation that may come in handy. If you need to make the DIV selectable/unselectable on the fly and are willing to use Modernizr, the following works neatly in javascript:

    var userSelectProp = Modernizr.prefixed('userSelect');
    var specialDiv = document.querySelector('#specialDiv');
    specialDiv.style[userSelectProp] = 'none';
链接地址: http://www.djcxy.com/p/72738.html

上一篇: 备用表格行颜色使用CSS?

下一篇: 有没有办法让DIV无法选择?