如何将 CSS 样式只应用于单词或者字符的半部分?

有时由于某些原因,我们需要将字符、单词或者整个句子设置为半样式。

为此,我们需要使用一些 CSS 和 JavaScript。

下面我们就来学习一下如何操作。

使用 CSS 的半样式

可以仅使用 CSS 将一个字符设置为半样式。

首先,将带有“linear-gradient”值的背景属性设置为我们喜欢的方向,并指定每种颜色的可见度为 50%。

然后,将 background-clip 属性设置为“text”,以便在前景文本中绘制背景。

下一步是设置 text-fill-color 属性,该属性指定元素文本内容的前景填充颜色。

设置 webkit-text-fill-color: 透明;让文本采用背景属性定义的颜色。

添加半样式字符的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      h1 {
        display: inline-block;
        margin: 0;
        line-height: 1em;
        font-family: Helvetica, Arial, sans-serif;
        font-weight: bold;
        font-size: 200px;
        background: linear-gradient(to right, #1c87c9 50%, #8ebf42 50%);
        background-clip: text;
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      }
    </style>
  </head>
  <body>
    <h1>X</h1>
    <p>This is a character with half-style.</p>
  </body>
</html>

如果我们只想拥有一个字符的一半并为其设置样式,只需为线性渐变的第二部分设置“透明”值。

添加透明半样式字符的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      h1 {
        display: inline-block;
        margin: 0;
        line-height: 1em;
        font-family: Helvetica, Arial, sans-serif;
        font-weight: bold;
        font-size: 200px;
        background: linear-gradient(to right, #1c87c9 50%, transparent 50%);
        background-clip: text;
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      }
    </style>
  </head>
  <body>
    <p>这个字符有透明的半样式。 选择它以查看它的隐藏部分。</p>
    <h1>X</h1>
  </body>
</html>

现在,让我们讨论一种情况,当我们需要一个半样式的单词而不是单个字符时。
这不是那么困难。
在这种情况下,我们只需要在 <span> 元素中设置每个字母,并为 <span> 元素应用上述相同的样式。

添加半样式字的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      span {
        display: inline-block;
        margin: 0;
        line-height: 1em;
        font-family: Helvetica, Arial, sans-serif;
        font-weight: bold;
        font-size: 60px;
        background: linear-gradient(to right, #1c87c9 50%, #113155 50%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      }
    </style>
  </head>
  <body>
    <div>
      <span>T</span>
      <span>E</span>
      <span>X</span>
      <span>T</span>
    </div>
  </body>
</html>

使用 JavaScript/jQuery 的半样式

查看另一个示例,其中 CSS ::before 伪元素与 JavaScript 一起使用。

我们还可以为半样式文本设置 text-shadow 属性。

使用 jQuery 添加半样式文本的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      body {
        font-family: Helvetica, Arial, sans-serif;
        font-size: 60px;
        font-weight: bold;
        text-align: center;
      }
      .half-style > span {
        white-space: pre-line;
        position: relative;
        color: #1c87c9;
      }
      .half-style > span::before {
        content: attr(data-content);
        pointer-events: none;
        position: absolute;
        overflow: hidden;
        color: #113155;
        width: 50%;
        z-index: 1;
      }
    </style>
  </head>
  <body>
    <div class='half-style'>onitroad</div>
    <script>
      function wrapString(str) {
        var output = [];
        str.split('')
          .forEach(function(letter) {
            var wrapper = document.createElement('span');
            wrapper.dataset.content = wrapper.innerHTML = letter;
            output.push(wrapper.outerHTML);
          });
        return output.join('');
      }
      window.onload = function() {
        var el = document.querySelector('.half-style')
          , txt = el.innerHTML;
        el.innerHTML = wrapString(txt);
      }
    </script>
  </body>
</html>

请参阅另一个示例,其中使用 jQuery 获得三重效果。

使用用于三重效果的 jQuery 添加半样式文本的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossoroirn="anonymous"></script>
    <style>
      .halfStyle {
        /* base char and also the right 1/3 */
        position: relative;
        display: inline-block;
        font-size: 80px;/* or any font size will work */
        color: transparent;/* hide the base character */
        overflow: hidden;
        white-space: pre;/* to preserve the spaces from collapsing */
        color: #1c87c9;/* for demo purposes */
        text-shadow: 2px 2px 0px #eee;/* for demo purposes */
      }

      .halfStyle:before {
        /* creates the left 1/3 */
        display: block;
        z-index: 2;
        position: absolute;
        top: 0;
        width: 33.33%;
        content: attr(data-content);/* dynamic content for the pseudo element */
        overflow: hidden;
        pointer-events: none;/* so the base char is selectable by mouse */
        color: #8ebf42;/* for demo purposes */
        text-shadow: 2px -2px 0px #eee;/* for demo purposes */
      }

      .halfStyle:after {
        /* creates the middle 1/3 */
        display: block;
        z-index: 1;
        position: absolute;
        top: 0;
        width: 66.66%;
        content: attr(data-content);/* dynamic content for the pseudo element */
        overflow: hidden;
        pointer-events: none;/* so the base char is selectable by mouse */
        color: #666;/* for demo purposes */
        text-shadow: 2px 2px 0px cyan;/* for demo purposes */
      }
    </style>
  </head>
  <body>
    <hr/>
    <p>Single Characters:</p>
    <span class="halfStyle" data-content="T">T</span>
    <span class="halfStyle" data-content="E">E</span>
    <span class="halfStyle" data-content="X">X</span>
    <span class="halfStyle" data-content="T">T</span>
    <hr/>
    <p>Automated on any text:</p>
    <span class="textToHalfStyle">Half-style text.</span>
    <hr/>
    <script>
      jQuery(function($) {
        var halfstyle_text, halfstyle_chars, $halfstyle_el, halfstyle_i, halfstyle_output, halfstyle_style;
        //Iterate over all class occurrences
        $('.textToHalfStyle')
          .each(function(idx, halfstyle_el) {
            $halfstyle_el = $(halfstyle_el);
            halfstyle_style = $halfstyle_el.data('halfstyle') || 'hs-base';
            halfstyle_text = $halfstyle_el.text();
            halfstyle_chars = halfstyle_text.split('');
            //Set the screen-reader text
            $halfstyle_el.html('<span style="position: absolute;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + halfstyle_text + '</span>');
            //Reset output for appending
            halfstyle_output = '';
            //Iterate over all chars in the text
            for (halfstyle_i = 0; halfstyle_i < halfstyle_chars.length; halfstyle_i++) {
              //Create a styled element for each character and append to container
              halfstyle_output += '<span aria-hidden="true" class="halfStyle ' + halfstyle_style + '" data-content="' + halfstyle_chars[halfstyle_i] + '">' + halfstyle_chars[halfstyle_i] + '</span>';
            }
            //Chrome 59 and above specific fix - Part 1 - Addresses a Chrome bug where Chrome fails to corectly render and repaint pseudo elements - I came up with this fix after many different tests.
            var _applyChromeFix = !!window.chrome && !!navigator.appVersion.match(/.*Chrome\/([0-9\.]+)/) && parseInt(navigator.appVersion.match(/.*Chrome\/([0-9\.]+)/)[1], 10) >= 59;
            if (_applyChromeFix) {
              halfstyle_output += '<style>.halfStyle{}</style>';
            }
            //Write to DOM only once
            $halfstyle_el.append(halfstyle_output);
            //Chrome 59 and above specific fix - Part 2
            if (_applyChromeFix) {
              setTimeout(function() {
                $halfstyle_el.find('style')
                  .remove();
              }, 0);
            }
          });
      });
    </script>
  </body>
</html>

垂直和水平半样式

定义半样式应该是垂直的还是水平的非常容易。
我们只需要指定线性渐变应该是从右到左还是从上到下。

添加垂直和水平半样式字母的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      .vertical {
        display: inline-block;
        margin: 0;
        line-height: 1em;
        font-family: Helvetica, Arial, sans-serif;
        font-weight: bold;
        font-size: 60px;
        background: linear-gradient(to right, #1c87c9 50%, #113155 50%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      }
      .horizontal {
        display: inline-block;
        margin: 0;
        line-height: 1em;
        font-family: Helvetica, Arial, sans-serif;
        font-weight: bold;
        font-size: 60px;
        background: linear-gradient(to top, #1c87c9 50%, #113155 50%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      }
    </style>
  </head>
  <body>
    <div>
      <h2>I am a vertically half-styled letter.</h2>
      <span class="vertical">X</span>
      <h2>I am a horizontally half-styled letter.</h2>
      <span class="horizontal">X</span>
    </div>
  </body>
</html>
日期:2020-06-02 22:14:57 来源:oir作者:oir