How to Make Text Unselectable in HTML?

DDD
Release: 2024-11-10 01:25:02
Original
346 people have browsed it

How to Make Text Unselectable in HTML?

How to Render Unselectable HTML Text: A Detailed Explanation

The question arises: how to make text on a webpage unselectable, preventing the cursor from changing to a text-selecting cursor upon hovering. This behavior is typically observed on buttons, such as those found on the Stack Overflow website.

CSS3 Solution

For modern browsers, a CSS3 solution suffices:

.unselectable {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
Copy after login

To apply this style, add the unselectable class to the label element:

<label class="unselectable">Unselectable label</label>
Copy after login

JavaScript Fallback

For older browsers, a JavaScript fallback is necessary:

function disableSelection(element) {
    if (typeof element.onselectstart != 'undefined') {
        element.onselectstart = function() { return false; };
    } else if (typeof element.style.MozUserSelect != 'undefined') {
        element.style.MozUserSelect = 'none';
    } else {
        element.onmousedown = function() { return false; };
    }
}

window.onload = function() {
    var labels = document.getElementsByTagName('label');
    for (var i = 0; i < labels.length; i++) {
        disableSelection(labels[i]);
    }
};
Copy after login

jQuery Solution

If jQuery is used, extend the disableSelection() function:

$.fn.extend({ 
    disableSelection: function() { 
        this.each(function() { 
            if (typeof this.onselectstart != 'undefined') {
                this.onselectstart = function() { return false; };
            } else if (typeof this.style.MozUserSelect != 'undefined') {
                this.style.MozUserSelect = 'none';
            } else {
                this.onmousedown = function() { return false; };
            }
        }); 
    } 
});
Copy after login

Then apply it to label elements:

$(document).ready(function() {
    $('label').disableSelection();            
});
Copy after login

The above is the detailed content of How to Make Text Unselectable in HTML?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template