Problem description

We know that the text on the browser page can be selected by double-clicking, or dragging the mouse horizontally. After selecting, you can right click to appear the panel and then copy something. But sometimes, we don’t want this effect, such as when the user clicked fast, so we need to disable this effect, this article notes how to disable the selected effect

The mouse is selected as follows

Method 1: Use the user-select attribute

CSS Settings user – select: none; If you need to do browser compatibility, please see the full text below:

The following code

<! DOCTYPEhtml>
<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 {
            / * * / firefox
            -moz-user-select: none;
            /* Safari and Openg */
            -webkit-user-select: none;
            /* IE10+ and Edge */
            -ms-user-select: none;
            /* Standard syntax */
            user-select: none;
        }
    </style>
</head>
<body>
    <h2>Hello CSS</h2>
</body>
</html>
Copy the code

Document.queryselector (‘h2’).style.userSelect = “None”

El-table also uses the user-select attribute

Review elements:

MDN official concept definition portal: developer.mozilla.org/zh-CN/docs/…

Method 2: OnselectStart event

Onselectstart is the event that when the user selects a DOM element, when it’s initially selected, it’s about to be selected, but it’s not actually selected. We just have to make the event return false, that is, end the event, so we don’t have the selected event, and we don’t have the effect that we don’t want, so here’s the code, two ways to write it

Notation one is on the label

<h2 onselectstart="return false;" </h2> </h2>

The second is in the form of a binding event

<body>
    <h2>Hello CSS, cannot be selected by mouse</h2>
    <script>
        document.querySelector('h2').onselectstart = function () {
            return false
        }
    </script>
</body>
Copy the code

conclusion

This paper introduces two ways to disable the selection effect, one is through CSS control, the other is through JS control. Note that if it is set to the body tag, the entire page of text is not selected…