开发者

Imitate "onselectstart=return false" using CSS or other non-JS approach? [duplicate]

开发者 https://www.devze.com 2022-12-10 03:54 出处:网络
This question already has answers here: Is there a way to make a DIV unselectable? (12 answers) 开发者_开发百科Closed 8 years ago.
This question already has answers here: Is there a way to make a DIV unselectable? (12 answers) 开发者_开发百科 Closed 8 years ago.

I have created a button CSS class that uses background images with different positions to display a different image on normal, mouseover, and click states. One thing completely destroying the visual effect is that if I click such a link repeatedly and move the mouse just a pixel, the link text gets selected.

Is there a way to achieve the effect of

onselectstart = "return false;"

without having to specify that for each button? A CSS based solution would be perfect, but I can't think of one. Any ideas?

One way would be iterating through each "button" element using prototype or JQuery and setting the onselectstart event manually. However I am allergic to Javascript when not absolutely necessary, and would appreciate any non-JS ideas.

Edit: I have found a solution for Mozilla browsers:

 -moz-user-select:none;


One thing completely destroying the visual effect is that if I click such a link repeatedly and move the mouse just a pixel, the link text gets selected.

Is it really a link? Normally you cannot select link text.

If you are using eg. a div as a faux-link, perhaps you ought to use a link instead (if it goes somewhere with a real href), or an input-button if it's just for scripting (although this requires some styling to lose the browser default styles, which is a bit of a pain).

Otherwise, Safari/Chrome/Konqueror replicates Mozilla's property under its own name:

-webkit-user-select: none;
-khtml-user-select: none;

For other browsers you need a JavaScript solution. Note onselectstart returning false is only sufficient in IE and Safari/Chrome; for Mozilla and Opera one would also have to return false onmousedown. This may also stop the click firing, so you would have to do whatever script stuff you have planned for the button in the mousedown handler before returning false, rather than onclick.

You can of course assign those handlers from script, to avoid messing up the markup, eg.:

<div class="button">...</div>

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

function returnfalse() {
    return false;
}

var divs= document.getElementsByTagName('div');
for (var i= divs.length; i-->0;)
    div.onselectstart= returnfalse;
0

精彩评论

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