7

两种方式实现css取消页面鼠标双击选中文字或单击拖动选中文字的效果

 3 years ago
source link: https://segmentfault.com/a/1190000040425848
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

我们知道浏览器页面上的文字正常情况下我们是可以双击选中、或者单击鼠标横向拖动也能选中的,选中以后可以右击出现面板然后去复制什么的。但是有的时候,这种效果我们并不想要的,比如用户点快了的时候,所以我们需要禁用这种效果,本文记录一下禁用选中效果的方式

鼠标选中的效果图如下

方式一:使用user-select属性

css设置user-select:none;即可,若需要做浏览器兼容处理,请看下方完整写法:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        h2 {
            /* 火狐 */
            -moz-user-select: none;
            /* Safari 和 欧朋 */
            -webkit-user-select: none;
            /* IE10+ and Edge */
            -ms-user-select: none;
            /* Standard syntax 标准语法(谷歌) */
            user-select: none;
        }
    </style>
</head>
<body>
    <h2>你好啊CSS</h2>
</body>
</html>

当然我们通过js选中dom元素去设置css样式也是可以的:document.querySelector('h2').style.userSelect = "none"

el-table也使用了user-select这个属性

审查元素图解一下:

MDN官方概念定义传送门:https://developer.mozilla.org...

方式二:onselectstart事件

onselectstart 就是用户选中DOM元素时候,被开始选中时,即将要被选中,实际未被选中的这个事件。我们只要让这个事件返回false,也就是结束这个事件,所以就不会有选中事件了,也就不会出现我们不想要的那种效果,代码如下,两种写法

写法一 写在标签上面

<h2 onselectstart="return false;">你好啊CSS,不能被鼠标选中</h2>

写法二 通过绑定事件的形式

<body>
    <h2>你好啊CSS,不能被鼠标选中</h2>
    <script>
        document.querySelector('h2').onselectstart = function () {
            return false
        }
    </script>
</body>

文中介绍了两种方式实现禁用选中效果,一种是通过css控制,另一种是通过js控制。注意,如果是设置在body标签上,那么整个页面的文字什么的都不能被选中了...


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK