Firefox has this annoying behavior that it let's the user drag and drop 开发者_如何学Cany image element by default. How can I cleanly disable this default behavior with jQuery?
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.
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 img
tags 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"
If Javascript is an optional requirement, you can try with CSS
.wrapper img {
pointer-events: none;
}
Solution without jQuery:
document.addEventListener('dragstart', function (e) {
e.preventDefault();
});
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;
});
You can cover your image with an empty div element:
.img-container{
position: relative;
}
.prevent-drag{
position: absolute;
width: 100%;
height: 100%;
z-index: 2;
}
<div class="img-container">
<div class="prevent-drag"></div>
<img src="" />
</div>
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>
精彩评论