Preventing an image from being draggable or selectable without using JS

前端 未结 8 2112
忘了有多久
忘了有多久 2020-12-04 05:28

Does anyone know of a way to make an image not draggable and not selectable -- at the same time -- in Firefox, without resorting to Javascript? Seems trivial, but here\'s th

8条回答
  •  死守一世寂寞
    2020-12-04 05:46

    I've been forgetting to share my solution, I couldn't find a way to do this without using JS. There are some corner cases where @Jeffery A Wooden's suggested CSS just wont cover.

    This is what I apply to all of my UI containers, no need to apply to each element since it recuses on all the child elements.

    CSS:

    .unselectable {
        /* For Opera and <= IE9, we need to add unselectable="on" attribute onto each element */
        /* Check this site for more details: http://help.dottoro.com/lhwdpnva.php */
        -moz-user-select: none; /* These user-select properties are inheritable, used to prevent text selection */
        -webkit-user-select: none;
        -ms-user-select: none; /* From IE10 only */
        user-select: none; /* Not valid CSS yet, as of July 2012 */
    
        -webkit-user-drag: none; /* Prevents dragging of images/divs etc */
        user-drag: none;
    }
    

    JS:

    var makeUnselectable = function( $target ) {
        $target
            .addClass( 'unselectable' ) // All these attributes are inheritable
            .attr( 'unselectable', 'on' ) // For IE9 - This property is not inherited, needs to be placed onto everything
            .attr( 'draggable', 'false' ) // For moz and webkit, although Firefox 16 ignores this when -moz-user-select: none; is set, it's like these properties are mutually exclusive, seems to be a bug.
            .on( 'dragstart', function() { return false; } );  // Needed since Firefox 16 seems to ingore the 'draggable' attribute we just applied above when '-moz-user-select: none' is applied to the CSS 
    
        $target // Apply non-inheritable properties to the child elements
            .find( '*' )
            .attr( 'draggable', 'false' )
            .attr( 'unselectable', 'on' ); 
    };
    

    This was way more complicated than it needed to be.

提交回复
热议问题