开发者

Making an element unselectable using jQuery

开发者 https://www.devze.com 2022-12-28 13:33 出处:网络
What\'s the best way to make an element unselectable using jQuery? I know you can use onselectstart=\"return false;\" ondragstart=\"return false;\" in the HTML, but I\'m not sure how cross browser co

What's the best way to make an element unselectable using jQuery?

I know you can use onselectstart="return false;" ondragstart="return false;" in the HTML, but I'm not sure how cross browser compatible that is.

I also see someone's made a jQuery plugin: http://plugins.jquery.com/project/Unselectable .. would a plugin like that be 开发者_如何学JAVAnecessary?

Is there a simple, compatible way to make an element unselectable?

The reason for wanting to do this is purely aesthetic. With webpages that have dragging or click events, it's not very nice when things get selected.


$('.noselect').live('selectstart dragstart', function(evt){ evt.preventDefault(); return false; });

Just bind the event to a live, and return false, or prevent default.


I think jQuery will abstract the browser variance & so it will help you make HTML elements unselectable.

Having said that, please note that the client can decide to switch off javascript, in which case you need to ensure that he still cannot do anything that will cause harm...

HTH.


I believe this is a better answer.

$('*[data-noselect="true"]').focus(
    function () {
        $(this).blur();
    });

$('*[data-noselect="true"] *').focus(
    function () {
        $(this).blur();
    });

Then you can just add a data-noselect="true" to any element.


If you use JqueryUI you can set class="ui-state-default" to the div that you dont want to be selected.

<div class="ui-state-default"></div>
0

精彩评论

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