1.禁止鼠标右键弹出菜单
document.oncontextmenu=newFunction("event.returnValue=false;");
document.onselectstart=newFunction("event.returnValue=false;");
2.兼容火狐失灵
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.onmousedown = norightclick; // for all others
延伸
1.禁止选择文本
var omitformtags=["input", "textarea", "select"];
omitformtagsomitformtags=omitformtags.join("|");
function disableselect(e){
if (omitformtags.indexOf(e.target.tagName.toLowerCase())==-1){
return false;
}
}
function reEnable(){
return true;
}
if (typeof document.onselectstart!="undefined"){
document.onselectstart=new Function ("return false");
}else{
document.onmousedown=disableselect;
document.onmouseup=reEnable;
}
2.禁止input/textarea内容被选中
document.querySelector('input').addEventListener('select',function(e){
var value = this.value;
this.value = '';
this.value = value;
})
document.querySelector('textarea').addEventListener('select',function(e){
var value = this.value;
this.value = '';
this.value = value;
})
3.屏蔽ctrl 按键(防止使用快捷键 【仅限Windows】)
document.onkeydown=function(){
if(event.ctrlKey){
return false;
}
}
附上html示例代码
<body>
<div class="poo">这个页面不能使用鼠标右键</div>
<input type="text" value="123" onclick = "fun()">
<textarea name="abc" id="abc" cols="30" rows="10">我们的我的不不都是 得不吧时间不加班 测试 测试测试</textarea>
<p>我的你的不是我们的值建的试试 逗我呢是设计的</p>
</body>
写在最后
禁止input 有很多种实现方法。比如user-select:none
这个兼容性不要忘记;disabled = disabled
这个属性。等等其他的,大家根据自己项目的十几需求要确认需要使用的方法。