How do we prevent default actions in JavaScript?

前端 未结 3 1901
情深已故
情深已故 2020-12-11 10:11

What is the cross-browser method? I need to prevent any default action on an image, so that neither dragging nor anything else will fire on a default bases.

相关标签:
3条回答
  • 2020-12-11 10:24

    You can only cancel specific events. You cannot "globally cancel" default actions.

    To specifically cancel dragging an image (which is only a default function in some browsers), return false to the mousedown event.

    0 讨论(0)
  • 2020-12-11 10:36
    (function() {
        var onmousedown;
        if('onmousedown' in document && typeof document.onmousedown == 'function') {
            onmousedown = document.onmousedown;
        }
        document.onmousedown = function(e) {
            if(typeof e == 'undefined') {
                e = window.event;
            }
            if(!e.target) {
                e.target = e.srcElement || document;
            }
            if('nodeName' in e.target && e.target.nodeName.toLowerCase() == 'img') {
                if(e.preventDefault) {
                    e.preventDefault();
                }
    
                // If you want to register mousedown events for
                // elements containing images, you will want to
                // remove the next four lines.
                if(e.stopPropagation) {
                    e.stopPropagation();
                }
                e.cancelBubble = true;
    
                e.returnValue = false;
                return false;
            }
    
            if(onmousedown !== undefined) {
                onmousedown(e);
            }
        };
    })();
    

    You may need to do something similar to other events you'd like to prevent, if this doesn't do what you want.

    Also it's worth noting that if you're trying to prevent people from downloading images from a page to their computer, you will not succeed. If a browser can download an image, so can the user. Using JavaScript to block (some) attempts is easily circumvented by simply disabling JavaScript.

    0 讨论(0)
  • You can register the events you want to cancel, and then either return false from them or use Event.preventDefault(), depending on the browser and event.

    0 讨论(0)
提交回复
热议问题