本文提供JavaScript代码示例,演示如何通过HTML属性及JS事件监听禁用鼠标右键、文本选择、粘贴与复制功能,并拦截Shift、Ctrl、Alt键及浏览器后退、刷新操作。
JavaScript实现禁用右键、选择、粘贴及特定键盘按键
以下直接提供相关实现代码。
具体代码示例如下:
<script language="JavaScript">
<!--
//js禁用某些键的代码
//www.jb51.net
function key(){
if(event.shiftKey){
window.close();}
//禁止Shift
if(event.altKey){
window.close();}
//禁止Alt
if(event.ctrlKey){
window.close();}
//禁止Ctrl
return false;}
document.onkeydown=key;
if (window.Event)
document.captureEvents(Event.MOUSEUP);
function nocontextmenu(){
event.cancelBubble = true
event.returnValue = false;
return false;}
function norightclick(e){
if (window.Event){
if (e.which == 2 || e.which == 3)
return false;}
else
if (event.button == 2 || event.button == 3){
event.cancelBubble = true
event.returnValue = false;
return false;}
}
//禁右键
document.oncontextmenu = nocontextmenu; // for IE5+
document.onmou<a href="https://www.jb51.net/article/1141.html" target="_blank" class="infotextkey">sed</a>own = norightclick; // for all others
//-->
</script>
在body标签中添加属性:<body onselectstart="return false"; onpaste="return false">
1. oncontextmenu="window.event.returnValue=false" 用于彻底屏蔽鼠标右键特效。例如在Table中使用:<table border oncontextmenu=return(false)><td>no</table>。
2. <body onselectstart="return false"> 用于取消文本选取并防止复制。
3. onpaste="return false" 用于禁止粘贴操作。
4. oncopy="return false;" 与 oncut="return false;" 用于防止复制和剪切操作。
补充说明:关于JS防止页面后退、刷新及关闭的解决方法。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head>
<title> New Document </title>
</head>
<script language="javascript">
function RunOnBeforeUnload() {window.onbeforeunload = function(){ return '将丢失未保存的数据!'; } }
</script>
<body onload="RunOnBeforeUnload()">
刷新,关闭,后退,F5 测试
</body>
</html>
尽管onbeforeunload事件已逐渐被Web标准淘汰,但当前仍能有效实现该效果,且主流浏览器均能良好支持。
测试结果表明:
IE6.0、FireFox及Chrome浏览器均通过测试。