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

How to Prevent Text Selection in HTML Labels?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-11 12:31:03691browse

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

Apply this class to the label element:

<label class="unselectable">Unselectable Label</label>

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"));

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

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

$("label").disableSelection();

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!

Statement:
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