纯CSS实现禁止网页文本被选中

CSS 属性 user-select 控制用户能否选中文本。利用这个css属性的特点,我们可以实现纯css禁止网页文本被选中. 首先我们来看一下css user-select属性语法及取值。

 

css user-select语法:

user-select:none |text| all | element

默认值:text

适用于:除替换元素外的所有元素

继承性:无

动画性:否

计算值:指定值

 

css user-select取值:

css user-select取值如下:

  • none:
  • 文本不能被选择
  • text:
  • 可以选择文本
  • all:
  • 当所有内容作为一个整体时可以被选择。如果双击或者在上下文上点击子元素,那么被选择的部分将是以该子元素向上回溯的最高祖先元素。
  • element:
  • 可以选择文本,但选择范围受元素边界的约束

 

user-select除Internet Explorer 9及其更早版本外,所有浏览器当前都支持。

.noselect {
  -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
     -khtml-user-select: none; /* Konqueror HTML */
       -moz-user-select: none; /* Old versions of Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome, Edge, Opera and Firefox */
}

关于这些样式的一些细节的解释:

  • -webkit-user-select是给Chrome,Safari和Opera用的(并不需要使用-o-user-select)。

  • 没有前缀的user-select是被故意略去的。

  • -webkit-touch-callout属性可以让在移动设备上的触摸后弹出失效。就像下面的这些,我们可以让它们不能出现。

 

CSS user-select实现禁止文本被选中

<style type="text/css">
.noselect {
  -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
     -khtml-user-select: none; /* Konqueror HTML */
       -moz-user-select: none; /* Old versions of Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome, Edge, Opera and Firefox */
}
</style>
<p>
  这段文本内容可以先被选中。
</p>
<p class="noselect">
  这段文本内容不能被选中。
</p>

以上就是本文的全部内容,希望对大家的学习有所帮助。更多教程请访问码农之家
posted @ 2022-08-24 13:12  small_123  阅读(389)  评论(0编辑  收藏  举报