Top
Fork me on Gitee

禁止文本复制,选择功能,禁用右键菜单功能

前言:网站会有一些简单的保密需求,不想让用户复制文字,或者轮播图到头了,左右箭头还在点点点,会有蓝色的背景,使用下面的css就可以解决这种问题。

CSS 属性禁止文本复制/选择功能

user-select 控制用户能否选中文本。除了文本框内,它对被载入为 chrome 的内容没有影响。

/* 禁止长按保存图片 */
img {
  pointer-events: none;
}

/* 禁止复制文本 */
/* *:not(input,textarea) 如果不是非要强制禁止选择,不要加*,否则修改某些元素可选时很麻烦 */
body {
  -webkit-touch-callout: none; /* iOS Safari */
  -webkit-user-select: none; /* Chrome/Safari/Opera */
  -khtml-user-select: none; /* Konqueror */
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* Internet Explorer/Edge */
  user-select: none; /* Non-prefixed version, currently not supported by any browser */
}

.select-none {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none
}

.select-text {
  -webkit-user-select: text;
  -moz-user-select: text;
  -ms-user-select: text;
  user-select: text
}

.select-all {
  -webkit-user-select: all;
  -moz-user-select: all;
  -ms-user-select: all;
  user-select: all
}

.select-auto {
  -webkit-user-select: auto;
  -moz-user-select: auto;
  -ms-user-select: auto;
  user-select: auto
}

jq 禁止右键菜单功能,禁止文本复制/选择功能

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

js 禁止右键菜单功能(兼容IE6-9)

document.body.onselectstart = document.body.ondrag = function() {
  return false;
}
document.addEventListener('contextmenu', function(event) {
  var e = event || window.event;
  // 阻止默认行为兼容写法
  if (e.preventDefault) {
    e.preventDefault() // w3c
  } else {
    e.returnValue = false // ie
  }
})
document.addEventListener('selectstart', function(e) {
  e.preventDefault(); 
})

拓展 CSS 改变选中样式

::selection CSS伪元素应用于文档中被用户高亮的部分(比如使用鼠标或其他选择设备选中的部分)。

只有一小部分CSS属性可以用于::selection 选择器:

color
background-color
cursor
caret-color
outline and its longhands
text-decoration and its associated properties
text-emphasis-color (en-US)
text-shadow
// 要特别注意的是,background-image 会如同其他属性一样被忽略。

CSS 示例

/* 选中的文本是红色背景,金黄色的字体 */
::selection {
  color: gold;
  background-color: red;
}

/*选中的是蓝色背景,白色的字体的段落*/
p::selection {
  color: white;
  background-color: blue;
}

注意

  1. selectstart 事件在用户开始一个新的选择时候触发。selectstart监听不能跟css配合使用,缺点:如果开始从指定可复制元素复制,不管结束在哪个元素都可以复制,这种效果不是我们想要的。
document.addEventListener('selectstart', function(e) {
  if(e.target.parentNode.className === 'select-text') {
    console.log('可以赋值,缺点:如果开始从指定可复制元素复制,不管结束在哪个元素都可以复制')
  } else {
    e.preventDefault(); 
  }
})
  1. user-select 不是继承属性,即使默认的属性值 auto 的表现基本上以继承为主,似乎是继承属性。甚至,WebKit/基于 Chromium 的浏览器在实现此属性时将其作为继承属性,但这和有关规范是相悖的,且会带来一些问题。目前,Chromium 暂时选择修复将其作为继承属性所带来的问题,使最终表现符合规范。

  2. a链接
    一个完整的a链接不能从中间部分复制;
    如果单独一个a连接可能会有复制不灵活或者只能从开始位置复制的问题,建议外面包裹div标签。

posted @ 2021-02-09 18:55  lisashare  阅读(429)  评论(0编辑  收藏  举报