Is it possible to apply CSS to half of a character?

后端 未结 19 1881
轻奢々
轻奢々 2020-11-22 16:46

What I am looking for:

A way to style one HALF of a character. (In this case, half the letter being transparent)

Wh

19条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 17:10

    Example


    JSFiddle DEMO

    We'll do it using just CSS pseudo selectors!

    This technique will work with dynamically generated content and different font sizes and widths.

    HTML:

    Two is better than one.

    CSS:

    .split-color > span {
        white-space: pre-line;
        position: relative;
        color: #409FBF;
    }
    
    .split-color > span:before {
        content: attr(data-content);
        pointer-events: none;  /* Prevents events from targeting pseudo-element */
        position: absolute;
        overflow: hidden;
        color: #264A73;
        width: 50%;
        z-index: 1;
    }
    

    To wrap the dynamically generated string, you could use a function like this:

    // Wrap each letter in a span tag and return an HTML string
    // that can be used to replace the original text
    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('');
    }
    
    // Replace the original text with the split-color text
    window.onload = function() {
        var el  = document.querySelector('.split-color'),
            txt = el.innerHTML;
        
        el.innerHTML = wrapString(txt);
    }
    

提交回复
热议问题