通过js和css禁止复制网页内容

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/fukaiit/article/details/100088076

注意:以下所有方法都不是完全可靠的,当用户禁用脚本或者F12去想办法复制的时候总是能复制的,只是相对提高了复制的麻烦程度而已。

方法1:在boby标签上添加各种禁止

<body οncοntextmenu="return false" 
	οndragstart="return false" 
	onselectstart ="return false" 
	οnselect="document.selection.empty()" 
	οncοpy="document.selection.empty()" 
	onbeforecopy="return false" 
	οnmοuseup="document.selection.empty()">
  • oncontextmenu="return false" 禁用右键菜单
  • ondragstart="return false" 禁止拖动
  • onselectstart ="return false" 禁止网页内容被选中
  • onselect="document.selection.empty()" 禁止文本框中的内容被选中
  • oncopy="document.selection.empty()" 禁止复制
  • onbeforecopy="return false" 禁止复制
  • onmouseup="document.selection.empty()"鼠标按键松开事件

缺点: 这是最鸡肋的一个方法,当网页不足一屏时,在body以外的位置还可以选中,Ctrl+C还是可以复制

方法2:通过js脚本控制-禁用上下文菜单、复制、选中等方法

其实本质和方法1相同,只是绑定到document上,就没有了方法1的致命缺点。
jQuery:

$(document).bind("contextmenu copy selectstart", function () {
	return false;
});

js:

document.oncontextmenu = new Function("event.returnValue=false");
document.onselectstart = new Function("event.returnValue=false");
document.oncopy = new Function("event.returnValue=false");

jQuery(允许文本框中复制):

$(document).bind("contextmenu copy selectstart", function(e) {
    if (!((e.target.tagName == "INPUT" && e.target.type.toLowerCase() == "text") || e.target.tagName == "TEXTAREA")) {
        return false;
    }
});

缺点: 如果用户禁用js,就凉凉了

方法3:通过js脚本控制-禁用复制快捷键Ctrl+C

禁用Ctrl+A和Ctrl+C快捷键

$(document).keydown(function(e) {
    if (e.ctrlKey && (e.keyCode == 65 || e.keyCode == 67)) {
        return false;
    }
});

缺点: 如果用户禁用js,就凉凉了

方法4:通过css控制

body {
    -moz-user-select: none;/* Firefox私有属性 */
    -webkit-user-select: none;/* WebKit内核私有属性 */
    -ms-user-select: none;/* IE私有属性(IE10及以后) */
    -khtml-user-select: none;/* KHTML内核私有属性 */
    -o-user-select: none;/* Opera私有属性 */
    user-select: none;/* CSS3属性 */
}

说明: body不足一屏没有问题,任何位置无法选中

综上:比较靠谱的综合方法

css:

body {
    -moz-user-select: none;/* Firefox私有属性 */
    -webkit-user-select: none;/* WebKit内核私有属性 */
    -ms-user-select: none;/* IE私有属性(IE10及以后) */
    -khtml-user-select: none;/* KHTML内核私有属性 */
    -o-user-select: none;/* Opera私有属性 */
    user-select: none;/* CSS3属性 */
}

js:

$(document).bind("contextmenu copy selectstart", function(e) {
    if (!((e.target.tagName == "INPUT" && e.target.type.toLowerCase() == "text") || e.target.tagName == "TEXTAREA")) {
        return false;
    }
});
$(document).keydown(function(e) {
    if (e.ctrlKey && (e.keyCode == 65 || e.keyCode == 67)) {
        return false;
    }
});

猜你喜欢

转载自blog.csdn.net/fukaiit/article/details/100088076