Home > Web Front-end > CSS Tutorial > How to Prevent Text Selection in HTML Labels?

How to Prevent Text Selection in HTML Labels?

Mary-Kate Olsen
Release: 2024-11-11 12:31:03
Original
742 people have browsed it

How to Prevent Text Selection in HTML Labels?

How to Effectively Prevent Text Selection in HTML

When creating a webpage, you may encounter the need to add labels that are unselectable by default. This can be particularly useful for buttons or navigation elements where you don't want the text to be copied or highlighted.

CSS-Based Solution (Modern Browsers)

For modern browsers that support CSS3, you can employ the following styles:

.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

Apply this class to the label element:

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

JavaScript Fallback (Older Browsers)

For older browsers that lack CSS3 support, you can use JavaScript to disable text selection:

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; };
    }
}

disableSelection(document.querySelector("label"));
Copy after login

This JavaScript function iterates through all labels on the page and applies the appropriate event handlers to disable selection.

jQuery Solution

If you're using jQuery, you can extend the jQuery library with the following code:

$.fn.disableSelection = function() { 
    this.each(function() {  
        disableSelection(this);
    }); 
};
Copy after login

Then, you can disable selection on all labels like so:

$("label").disableSelection();
Copy after login

The above is the detailed content of How to Prevent Text Selection in HTML Labels?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template