什么是跨浏览器的方法?我需要防止任何默认操作在图像上,以便既不拖动也不会发生其他默认行为。
您可以注册要取消的事件,然后根据浏览器和事件使用return false
或Event.preventDefault()
。
(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);
}
};
})();
您只能取消特定事件。您无法“全局取消”默认操作。
要特别取消图像的拖动
(这只是某些浏览器中的默认功能),请在mousedown
事件中返回false
。
document.onmousedown = function(e) { if(typeof e == 'undefined') e = window.event; if(e.preventDefault) e.preventDefault(); if(e.stopPropagation) e.stopPropagation(); e.returnValue = false; return false; };
但显然这将产生大量不良副作用。 - eyelidlessness