头图

Problem Description

We know that under normal circumstances, the text on the browser page can be selected by double-clicking, or by clicking the mouse and dragging it horizontally. After selecting, you can right-click to display the panel and copy or something. But sometimes, this effect is not what we want, such as when the user clicks quickly, so we need to disable this effect. This article records the way to disable the selected effect.

The effect diagram selected by the mouse is as follows

Method 1: Use the user-select attribute

user-select:none; can be set to 06102a65fd61c5. If you need to do browser compatibility processing, please see the complete writing below:

code show as below

<!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>
Of course, it is also possible for us to select the dom element through js to set the css style: document.querySelector('h2').style.userSelect = "none"

el-table also uses the user-select attribute

Illustrate the review elements:

MDN official concept definition portal: https://developer.mozilla.org/zh-CN/docs/Web/CSS/user-select

Method 2: onselectstart event

onselectstart is the event when the user selects a DOM element and is about to be selected when the DOM element is selected, but is not actually selected. As long as we let this event return false, that is, end this event, so there will be no selected event, and the effect we don’t want will not appear. The code is as follows, two ways of writing

Write it on the label

<h2 onselectstart="return false;">Hello CSS, can’t be selected by the mouse</h2>

The second way of writing is through the form of binding events

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

Summarize

The article introduces two ways to achieve the disabled selection effect, one is through css control, the other is through js control. Note that if it is set on the body tag, then the text of the entire page cannot be selected...


水冗水孚
1.1k 声望588 粉丝

每一个不曾起舞的日子,都是对生命的辜负