How to disable Firefox's default drag and drop on all images behavior with jQuery?

﹥>﹥吖頭↗ 提交于 2019-12-20 12:31:06

问题


Firefox has this annoying behavior that it let's the user drag and drop any image element by default. How can I cleanly disable this default behavior with jQuery?


回答1:


The following will do it in Firefox 3 and later:

$(document).on("dragstart", function() {
     return false;
});

If you would prefer not to disable all drags (e.g. you may wish to still allow users to drag links to their link toolbar), you could make sure only <img> element drags are prevented:

$(document).on("dragstart", function(e) {
     if (e.target.nodeName.toUpperCase() == "IMG") {
         return false;
     }
});

Bear in mind that this will allow images within links to be dragged.




回答2:


Does it need to be jQuery? You just need to define a callback function for your mousedown event on the image(s) in question with event.preventDefault().

So your image tag could look like this:

<img src="myimage.jpg" onmousedown="if (event.preventDefault) event.preventDefault()" />

The additional if is needed because otherwise IE throws an error. If you want this for all image tags you just need to iterate through the imgtags with jQuery and attach the onmousedown event handler.

There is a nice explanation (and example) on this page: "Disable image dragging in FireFox" and a not as well documented version is here using jQuery as reference: "Disable Firefox Image Drag"




回答3:


Solution without jQuery:

document.addEventListener('dragstart', function (e) {
    e.preventDefault();
});



回答4:


If Javascript is an optional requirement, you can try with CSS

.wrapper img {
    pointer-events: none;
}



回答5:


Referencing Tim Down's solution, you can achieve the equivalent of his second code snippet of only disabling img drags while using jQuery:

$(document).on("dragstart", "img", function() {
     return false;
});



回答6:


I don't remember my source but work

  <script type="text/javascript">

  // register onLoad event with anonymous function
window.onload = function (e) {
    var evt = e || window.event,// define event (cross browser)
        imgs,                   // images collection
        i;                      // used in local loop
    // if preventDefault exists, then define onmousedown event handlers
    if (evt.preventDefault) {
        // collect all images on the page
        imgs = document.getElementsByTagName('img');
        // loop through fetched images
        for (i = 0; i < imgs.length; i++) {
            // and define onmousedown event handler
            imgs[i].onmousedown = disableDragging;
        }
    }
};

// disable image dragging
function disableDragging(e) {
    e.preventDefault();
}
</script>


来源:https://stackoverflow.com/questions/3873595/how-to-disable-firefoxs-default-drag-and-drop-on-all-images-behavior-with-jquer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!