如何使用 CSS 禁用文本选择高亮?
在 CSS 中,我们可以使用 select 属性禁用文本选择高亮。但要禁用文本选择高亮,我们必须在 CSS 中应用一些属性,使文本无法被选中或高亮。让我们通过一个例子来理解高亮文本和非高亮文本之间的区别。
Tutorialspoint − 文本已高亮。
Tutorialspoint − 文本未高亮。
使用的属性
示例中使用了以下属性 −
user-select − 此属性定义用户是否选择了文本元素。 Chrome 和 Opera 浏览器支持此属性。
moz-user-select − 此属性的作用与 user-select 属性相同,Mozilla Firefox 浏览器支持此属性。
webkit-text-select − iOS Safari 浏览器支持此属性,其作用与 user-select 属性相同。
webkit-user-select − 此属性的作用与 user-select 属性相同。Safari 浏览器支持此属性。
示例 1
在此示例中,我们将首先使用 h1 元素和 p 元素设置文本段落,从而设置文本的主标题。要禁用段落文本选择高亮功能,它将使用内部 CSS 来启动 p 元素的类,即".no-highlight"。该类将浏览器属性 user-select 的值设置为 none(Chrome 和 Opera 浏览器禁用文本选择)。
<!DOCTYPE html>
<html>
<title>Tutorialspoint</title>
<head>
<style>
.not-active{
user-select: none; // chrome and Opera
}
</style>
</head>
<body>
<center>
<h1>The Story of Helen Keller</h1>
</center>
<p class="not-active">Helen Keller (born June 27, 1880, in Tuscumbia, Alabama, U.S.—died June 1, 1968, in Westport, Connecticut) was a blind and deaf American author and schoolteacher. Keller lost her eyes and hearing at the age of 19 months due to illness, and her speech development followed suit. Anne Sullivan (1866-1936), who taught her the names of things by pressing the manual alphabet into her palm, started instructing her five years later. Keller eventually learned to read and write in Braille. She was the author of several works, including The Story of My Life. (1902). William Gibson's play The Miracle Worker depicted her upbringing. (1959; film, 1962).</p>
<p>
<b>@tutorialspoint<b>
</p>
</body>
</html>
示例 2
在本例中,我们将使用 p 元素创建两个段落,以区分启用和禁用文本选择。第一个段落只是文本的简单表示,表示文本已启用;而第二个段落则设置了名为 ".no-highlight" 的类。然后使用内部 CSS 引用此引用,并通过设置不同的浏览器属性来禁用文本选择。
<!DOCTYPE html>
<html>
<title>Online HTML Editor</title>
<head>
<style>
.no-highlight{
user-select: none; // chrome and Opera
-moz-user-select: none; // Firefox
-webkit-text-select: none; // IOS Safari
-webkit-user-select: none; // Safari
}
</style>
</head>
<body>
<h1>Disable the text selection highlighting using CSS</h1>
<p>The text can be highlighted</p>
<p class="no-highlight">The text cannot be highlighted</p>
</body>
</html>
结论
我们通过启用和禁用文本高亮功能理解了它的概念。在上面的输出中,可以看到,当光标移动到文本上时,第一个文本会被高亮显示;而在第二段中,由于在内部 CSS 中使用了禁用浏览器属性,因此文本并未被高亮显示。
相关文章
有用资源
css 参考教程 - 该教程包含有关 css 的更多信息:https://www.cainiaomax.com/css/

