首页 >web前端 >css教程 >如何使 HTML 中的文本不可选择?

如何使 HTML 中的文本不可选择?

DDD
DDD原创
2024-11-10 01:25:02485浏览

How to Make Text Unselectable in HTML?

如何渲染不可选择的 HTML 文本:详细说明

问题来了:如何使网页上的文本不可选择,防止光标移动从悬停时更改为文本选择光标。这种行为通常出现在按钮上,例如 Stack Overflow 网站上的按钮。

CSS3 解决方案

对于现代浏览器,CSS3 解决方案就足够了:

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

要应用此样式,请将不可选择的类添加到标签元素:

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

JavaScript 后备

对于较旧的浏览器,JavaScript 后备是必需的:

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

jQuery 解决方案

如果使用 jQuery,请扩展disableSelection() 函数:

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

然后应用它标记元素:

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

以上是如何使 HTML 中的文本不可选择?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn