代码之家  ›  专栏  ›  技术社区  ›  Darren

在任何HTML元素上覆盖半透明框

  •  0
  • Darren  · 技术社区  · 7 年前

    我有一个html文件 无法控制的内容 是的。我所能做的就是插入一个css文件和/或javascript文件(如果需要,包括jquery之类的库)。

    在HTML中,有些元素需要突出显示并添加工具提示(例如,它们有一个特定的数据属性),但是它们不方便位于我可以应用样式的特定容器中。这些元素可能是 <span> 我是说, <a> 我是说, <img> 我是说, <div> 或者其他任何东西(内联或块)。

    如果可以的话,我想用纯css来解决这个问题,但是如果需要的话,我愿意使用javascript来修改dom,但是最终的html必须具有与原始html相同的布局,即在特定元素上浮动的突出部分。

    例如,我可能有这样的html:

    <body>
        <p>This is a sample line of text with <a href="#">a link</a> in the middle that should be highlighted</p>
    
        <p>This is a sample line of text with <a href="#" data-highlight="true">a link</a> in the middle that should be highlighted</p>
    </body>
    

    结果应该是这样的:

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  3
  •   Andrzej Ziółek    7 年前

    我想买这样的东西。正如你所希望的,只有css,html没有变化。

    • *[data-highlight="true"] -选择所有元素 data-highlight="true"

    • background: rgba(255, 0, 0, 0.5) -提供50%不透明度的RGBA背景。

    要记住的事情

    如果有一些元素具有特定的css规则,则需要对代码下面的位置进行调整。例如,如果 <span> 需要有以下规则,但已经有 position: absolute 位置值不能更改为 relative 并且下面必须覆盖特定规则。

    片段

    *[data-highlight="true"] {
      position: relative;
    }
    
    *[data-highlight="true"]:after {
      display: block;
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      height: 100%;
      width: 100%;
      background: rgba(255, 0, 0, 0.5);
      border: 1px solid red;
    }
    <body>
      <p>This is a sample line of text with <a href="#">a link</a> in the middle that should be highlighted</p>
    
      <p>This is a sample line of text with <a href="#" data-highlight="true">a link</a> in the middle that should be highlighted</p>
    </body>