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

如何实现正则表达式模式文本框内的预设修饰符不可选中

正则输入框预设修饰符不可选中实现方案

核心逻辑是拆分固定修饰符和输入区域,不要把所有内容都放在同一个原生输入框内:

  • 两侧的固定修饰符用普通DOM元素渲染,禁止选中
  • 中间的可编辑区域用原生输入框/可编辑标签实现,和两侧修饰符做视觉融合即可

方案1:input + 修饰符标签组合(兼容性最好)

代码结构

<div class="regex-input-wrapper">
  <span class="regex-modifier">/</span>
  <input type="text" class="regex-pattern-input" placeholder="输入正则表达式">
  <span class="regex-modifier">/gim</span>
</div>

样式代码

.regex-input-wrapper {
  display: inline-flex;
  align-items: center;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  padding: 6px 10px;
  font-family: monospace;
  font-size: 14px;
}
.regex-modifier {
  /* 核心:禁止用户选中 */
  user-select: none;
  color: #6b7280;
}
.regex-pattern-input {
  border: none;
  outline: none;
  background: transparent;
  font-family: inherit;
  font-size: inherit;
  padding: 0 6px;
  min-width: 220px;
}

提交拼接逻辑

如果需要提交完整带修饰符的正则,直接在JS层拼接即可:

const getFullRegex = () => {
  const prefix = document.querySelector('.regex-modifier:first-child').textContent
  const inputVal = document.querySelector('.regex-pattern-input').value
  const suffix = document.querySelector('.regex-modifier:last-child').textContent
  return prefix + inputVal + suffix
}

方案2:contenteditable容器实现(灵活度更高)

如果需要支持更复杂的输入样式,可以用可编辑容器实现,修饰符直接标记为不可编辑即可:

<div class="regex-input-container" contenteditable="true">
  <span contenteditable="false">/</span>
  <span class="input-area"></span>
  <span contenteditable="false">/gim</span>
</div>

contenteditable="false"的元素天然不可选中、不可编辑,不需要额外加禁止选中的样式,视觉上可以完全模拟成一个整体输入框。

你之前排查样式没找到实现,大概率是站点把user-select属性写到了通用工具类里,或者用了第二种contenteditable方案,没有单独给修饰符写特殊样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 02:45:05