新的项目中要求在图片上不能进行点击下载,针对小白进行简单防盗链防下载!我想到了contextmenu事件控制右键事件,且兼容所有主流浏览器。实现原理是绑定contextmenu事件,阻止浏览器的默认事件,显示你的自定义菜单(或者直接阻止,以达到屏蔽右键菜单的效果)。
代码如下 | 复制代码 |
window.onload = function(e) { var showimgtag = document.getElementById('showimgtag'), showimgtagF = showimgtag.parentNode, menu = document.getElementById('menu'); addHandler(showimgtag, 'contextmenu', function(e){ e = e || window.event; preventDefault(e); menu.style.left = e.pageX+'px'; menu.style.top = e.pageY+'px'; menu.style.display = 'block'; menu.innerHTML = '© '+'author'; }); addHandler(menu, 'contextmenu', function(e){ e = e || window.event; preventDefault(e); }); addHandler(document, 'mousedown', function(e){ e = e || window.event; var obj = e.srcElement?e.srcElement:e.target; if(isChild(menu, obj)){ return false; } menu.style.display = 'none'; }); }; function isChild(parent, child) { while (child != null) { if (child == parent) { return true; } child = child.parentNode; } return false; } function addHandler(element, type, handler) { if(element.addEventListener){ element.addEventListener(type,handler,false); }else{ element.attachEvent('on'+type,handler); } } function preventDefault(e){ e = e || window.event; if(e.preventDefault){ e.preventDefault(); }else{ e.returnValue = false; } } |
时间: 2024-11-08 19:16:12