JS禁用右键、选择、复制、键盘

在框架中使用直接看最后面

JS禁用鼠标右键

// 禁用右键默认行为
document.oncontextmenu = function (evt) {
    
    
   evt.preventDefault();
};

// 属性返回false
document.oncontextmenu = function(evt) {
    
    
    evt.returnValue = false;
}

// 或者直接返回整个事件
document.oncontextmenu = function(){
    
    
    return false;
}

JS禁用复制

document.oncopy = function(evt) {
    
    
    evt.returnValue = false;
}

// 整个事件直接返回false
document.oncopy = function(){
    
    
    return false;
}

JS禁用选择

document.onselectstart = function(evt) {
    
    
    evt.returnValue = false;
}

// 整个事件直接返回false
document.onselectstart = function(){
    
    
    return false;
}

JS禁用某个按键

document.onkeydown = function (evt) {
    
    
	// 想禁用什么键按下键盘看他的属性, 然后判断返回false
   console.log(evt, '键盘属性')
    if (evt.key === 'F12') return false
}

在React框架中使用

在框架的某个组件中使用禁止右键

在框架的某个组件中使用禁止右键
class Dome extends Component {
    
    

	// 在这个生命周期函数中添加
	componentDidMount() {
    
    
		// 添加禁止右键的函数
	    document.addEventListener('contextmenu', this.handleContextmenu)
	}
	
	// 在这个生命周期函数中移除
	componentWillUnmount() {
    
    
		// 移除禁止右键
	    document.removeEventListener('contextmenu', this.handleContextmenu)
	}
	
	// 禁止右键函数
	handleContextmenu = (evt) => {
    
    
	    evt.preventDefault()
	}

	render() {
    
    
		return(<div>现在当前组件是禁止右键的</div>)
	}
 }

export default Dome 

react全局禁用鼠标右键

需要找到你项目的入口文件

<!DOCTYPE html>
<html lang="cn">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>全局禁用</title>
  <link rel="icon" href="/favicon.png" type="image/x-icon">
  <script src="https://gw.alipayobjects.com/os/antv/pkg/_antv.data-set-0.9.6/dist/data-set.min.js"></script>
</head>
<body>
<div id="root"></div>

<script>
	// 在入口文件中加入禁用右键的代码
	document.oncontextmenu = function (evt) {
    
    
		evt.preventDefault()
	}
</script>

</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_44953227/article/details/103773644
今日推荐