You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS禁用页面文本选择时,如何正确排除input/textarea元素?

全局禁用文本选择但保留输入框权限的解决方案

正确实现代码

/* 全局禁用页面文本选择 */
body {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* 恢复输入框的文本选择权限 */
input, textarea {
  -webkit-touch-callout: default;
  -webkit-user-select: text;
  -khtml-user-select: text;
  -moz-user-select: text;
  -ms-user-select: text;
  user-select: text;
}

/* 自定义非输入框的选中样式(可选) */
::selection {
  background-color: transparent;
}

/* 恢复输入框的默认选中样式(可选,也可自定义颜色) */
input::selection, textarea::selection {
  background-color: initial;
}

你之前代码的问题解析

  1. :not()选择器的用法错误
    你写的*:not(input):not(textarea)会匹配所有非输入框的元素,包括输入框的父元素。由于user-select是继承属性,父元素的user-select: none会传递给输入框,导致输入框也失去选择权限。而你后来用的* :not(input):not(textarea)(带空格)是后代选择器,只匹配非输入框的子元素,父元素不受影响,输入框才正常,但这种写法效率低且逻辑不严谨。

  2. ::selection的语法错误
    ::selection是伪元素,不能和:not()伪类链式组合成::selection::not(...),这种写法不符合CSS语法规范,浏览器根本无法识别,导致整个规则失效。

方案优势

  • 性能更优:用body代替*选择器,减少不必要的元素匹配,降低浏览器渲染开销。
  • 逻辑清晰:先全局禁用,再针对性恢复输入框权限,避免复杂选择器带来的继承问题。
  • 兼容性强:避开:not()选择器在旧浏览器的潜在兼容问题,明确指定输入框的user-select值,确保覆盖继承样式。

内容的提问来源于stack exchange,提问作者Marc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 06:41:34