当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - unselectable works in Firefox/Chrome/Safari, not working IE8

问题描述:

I need to be able to prevent from an image (placed in a DIV) of being selected.

I've tried many suggestion, but none seem to work on IE8.

The fact is, when the user selects the text with the mouse, in IE8 (and only IE8) the image gets selected as well.

It appeared the simpliest to upload an example to the web (rather than to here) so you can find the example in

http://www.enosis-dev.com/select.html

click view source to see the code.

Any help will be appreciated.

Nir.

网友答案:

Use a <div> with a background image instead of an <img>. If the image in question is 100px by 50px (for example), then something like this should do the trick:

<div style="display: inline-block; width: 100px; height: 50px: background: url(/path/to/image.jpg);"></div>

If you need to support IE7 then you'll probably have to change display: inline-block to display: block using an IE7-specific stylesheet (preferably loaded using a conditional comment).

The problem with the above is that you need to know the image dimensions before replacing the <img> tags with <div> tags with backgrounds. You can do the replacement on the client side using jQuery to get around that problem but some care is needed to ensure that the images are loaded before they're replaced:

$(window).load(function() {
    $('img').each(function() {
        var $img         = $(this);
        var $replacement = $('<div/>');
        $replacement.css({
            width:      $img.width()  + 'px',
            height:     $img.height() + 'px',
            display:    'inline-block',
            background: 'url(' + $img.attr('src') + ')'
        });
        $img.after($replacement).remove();
    });
});

$(window).load() shouldn't fire until everything is loaded so all the image sizes should be known when it does.

If IE7 is an issue then you can put the display: inline-block bit in a class and override it using an IE7-specific stylesheet in the usual way.

网友答案:

Try
ele.onselectstart = function (){ return false; }

ele.unselectable = "on";

Or Try
user-select: none; -webkit-user-select: none; -o-user-select: none; -moz-user-select: none;

分享给朋友:
您可能感兴趣的文章:
随机阅读: