突出显示文本而不突出显示/选择整个元素 - 是否可以避免虚拟元素?

dar*_*her 5 javascript css user-experience

目标:仅突出显示文本,而不突出显示空白。

对我来说,当实现大的填充、行高等(现在可以突出显示的空白)时,突出显示整个元素可能会导致一些不规则和糟糕的用户体验。像突出显示文本块这样简单的任务可能会反过来突出显示用户不想要的网站其他区域。我正在尝试在当前站点上解决此问题,但只能通过使用下面提供的方法来实现。

其中,我在块级元素内使用内联元素。正如您可能注意到的,如果在整个网站中使用它,可能会变得非常麻烦且代码繁重。有没有更好的方法来实现第二种方法?

我对 Javascript 解决方案和 CSS 持开放态度。

据我所知(通过测试),如果复制+粘贴到 Word 文档或网络邮件应用程序(例如 gmail)中,它的渲染效果不会有所不同。如果您知道这可能会导致任何问题,请在下面提及。

为了更好地说明:

随着突出显示的改进: 在此输入图像描述 没有突出显示改进: 在此输入图像描述

^诚然,这是一个半途而废的例子,它展示了它可以派上用场的实例之一,还有很多其他实例,相信我。

.highlight-text-only > *{
display:block;
  -webkit-user-select: none;
 -moz-user-select: none;
  -ms-user-select: none;
   -o-user-select: none;
      user-select: none}

.highlight-text-only *>span,
.highlight-text-only *>strong{
display:inline;
  -webkit-user-select: text;
 -moz-user-select: text;
  -ms-user-select: text;
   -o-user-select: text;
      user-select: text}
Run Code Online (Sandbox Code Playgroud)
<div class="highlight-text-and-element">
  <h3>Testing Text Selection Method 1 (default)</h3>
  <div>of only text</div>
  <a href="#"><strong>with</strong></a>
  <p>highlighting</p>
  <span>the actual elements</span>
</div>

<hr>

<div class="highlight-text-only">
  <h3><span>Testing Selection Method 2</span></h3>
  <div><span>of only text</span></div>
  <a href="#"><strong>without</strong></a>
  <p><span>highlighting</span></p>
  <span><span>the actual elements</span></span>
</div>
Run Code Online (Sandbox Code Playgroud)

Cup*_*Tae 2

您无法直接使用 CSS 定位 DOM 中的文本节点,但您可以使用 javascript 找到它们,并以编程方式将它们包装在<span>s 中,以达到相同的效果,同时保持标记干净:

function wrapText(nodes, className) {
  for (var i=0,len=nodes.length; i<len; i++) {
    var node=nodes[i];
    
    if (node.nodeType == 3) {
      var wrapper=document.createElement("span");
      wrapper.className = className;
      node.parentNode.insertBefore(wrapper,node);
      wrapper.appendChild(node);
    } else {
      wrapText(node.childNodes, className);
    }
  }
}

wrapText(document.querySelectorAll(".highlight-text-only"),"selectme");
Run Code Online (Sandbox Code Playgroud)
.highlight-text-only {
  -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none;
  user-select: none;
}

.highlight-text-only .selectme {
  -webkit-user-select: text; -moz-user-select: text; -ms-user-select: text; -o-user-select: text;
  user-select: text;
}
Run Code Online (Sandbox Code Playgroud)
<div class="highlight-text-and-element">
  <h3>Testing Text Selection Method 1 (default)</h3>
  <div>of only text</div>
  <a href="#"><strong>with</strong></a>
  <p>highlighting</p>
  <span>the actual elements</span>
</div>

<hr>

<div class="highlight-text-only">
  <h3>Testing Selection Method 2</h3>
  <div>of only text</div>
  <a href="#"><strong>without</strong></a>
  <p>highlighting</p>
  <span>the actual elements</span>
</div>
Run Code Online (Sandbox Code Playgroud)