是否可以将CSS应用于角色的一半?

时间:2014-05-09 16:16:57

标签: javascript html css css3

我在寻找什么:

设置角色的一个 HALF 的方式。 (在这种情况下,一半字母是透明的)

我目前搜索并尝试过的内容(没有运气):

  • 为一半字符/字母设置样式的方法
  • 使用CSS或JavaScript设置角色的一部分
  • 将CSS应用于角色的50%

下面是我想要获得的一个例子。

x

是否存在CSS或JavaScript解决方案,或者我将不得不诉诸图像?我宁愿不去图像路线,因为这个文本最终会动态生成。


更新

因为很多人都问过为什么我想要设置一半角色,这就是原因。我的城市最近花了25万美元为自己定义一个新的“品牌”。 logo 就是他们想出来的。许多人抱怨简单性和缺乏创造力,并继续这样做。我的目标是将这个 website 作为一个笑话。输入'哈利法克斯',你会看到我的意思。

20 个答案:

答案 0 :(得分:2793)

Now on GitHub as a Plugin!

enter image description here随意分叉和改进。

Demo | Download Zip | Half-Style.com(重定向到GitHub)


  • 单个字符的纯CSS
  • 用于跨文本或多个字符进行自动化的JavaScript
  • 为盲人或视觉上的屏幕阅读器保留文本可访问性 障

第1部分:基本解决方案

Half Style on text

演示: http://jsfiddle.net/arbel/pd9yB/1694/


这适用于任何动态文本或单个字符,并且都是自动化的。您需要做的就是在目标文本上添加一个类,其余的都要处理。

此外,为盲人或视障人士的屏幕阅读器保留原始文本的可访问性。

单个字符的说明:

纯CSS。您需要做的就是将.halfStyle类应用于包含您想要半个样式的字符的每个元素。

对于包含该字符的每个span元素,您可以创建一个数据属性,例如data-content="X",并在伪元素上使用content: attr(data-content);,这样.halfStyle:before类将是动态的,你不需要为每个实例硬编码。

任何文字说明:

只需将textToHalfStyle类添加到包含文本的元素中。


// jQuery for automated mode
jQuery(function($) {
    var text, chars, $el, i, output;

    // Iterate over all class occurences
    $('.textToHalfStyle').each(function(idx, el) {
    $el = $(el);
    text = $el.text();
    chars = text.split('');

    // Set the screen-reader text
    $el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');

    // Reset output for appending
    output = '';

    // Iterate over all chars in the text
    for (i = 0; i < chars.length; i++) {
        // Create a styled element for each character and append to container
        output += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';
    }

    // Write to DOM only once
    $el.append(output);
  });
});
.halfStyle {
    position: relative;
    display: inline-block;
    font-size: 80px; /* or any font size will work */
    color: black; /* or transparent, any color */
    overflow: hidden;
    white-space: pre; /* to preserve the spaces from collapsing */
}

.halfStyle:before {
    display: block;
    z-index: 1;
    position: absolute;
    top: 0;
    left: 0;
    width: 50%;
    content: attr(data-content); /* dynamic content for the pseudo element */
    overflow: hidden;
    color: #f00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p>Single Characters:</p>
<span class="halfStyle" data-content="X">X</span>
<span class="halfStyle" data-content="Y">Y</span>
<span class="halfStyle" data-content="Z">Z</span>
<span class="halfStyle" data-content="A">A</span>

<hr/>
<p>Automated:</p>

<span class="textToHalfStyle">Half-style, please.</span>

JSFiddle demo


第2部分:高级解决方案 - 独立的左右部分

Half Style on text - advanced - With Text Shadow

使用此解决方案,您可以单独和独立地设置左右部分的样式

一切都是一样的,只有更高级的CSS才能发挥作用。

jQuery(function($) {
    var text, chars, $el, i, output;

    // Iterate over all class occurences
    $('.textToHalfStyle').each(function(idx, el) {
        $el = $(el);
        text = $el.text();
        chars = text.split('');

        // Set the screen-reader text
        $el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');

        // Reset output for appending
        output = '';

        // Iterate over all chars in the text
        for (i = 0; i < chars.length; i++) {
            // Create a styled element for each character and append to container
            output += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';
        }

        // Write to DOM only once
        $el.append(output);
    });
});
.halfStyle {
    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 */
}

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

.halfStyle:after { /* creates the right part */
    display: block;
    direction: rtl; /* very important, will make the width to start from right */
    position: absolute;
    z-index: 2;
    top: 0;
    left: 50%;
    width: 50%;
    content: attr(data-content); /* dynamic content for the pseudo element */
    overflow: hidden;
    pointer-events: none; /* so the base char is selectable by mouse */
    color: #000; /* for demo purposes */
    text-shadow: 2px 2px 0px #0af; /* for demo purposes */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Single Characters:</p>
<span class="halfStyle" data-content="X">X</span>
<span class="halfStyle" data-content="Y">Y</span>
<span class="halfStyle" data-content="Z">Z</span>
<span class="halfStyle" data-content="A">A</span>

<hr/>
<p>Automated:</p>

<span class="textToHalfStyle">Half-style, please.</span>

JSFiddle demo



第3部分:混合匹配和改进

现在我们知道什么是可能的,让我们创造一些变化。


- 水平半部件

  • 没有文字阴影:

    Horizontal Half Parts - No Text Shadow

  • 文本阴影的可能性为每个半部分独立:

    halfStyle - Horizontal Half Parts - With Text Shadow

// jQuery for automated mode
jQuery(function($) {
    var text, chars, $el, i, output;

    // Iterate over all class occurences
    $('.textToHalfStyle').each(function(idx, el) {
        $el = $(el);
        text = $el.text();
        chars = text.split('');

        // Set the screen-reader text
        $el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');

        // Reset output for appending
        output = '';

        // Iterate over all chars in the text
        for (i = 0; i < chars.length; i++) {
            // Create a styled element for each character and append to container
            output += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';
        }

        // Write to DOM only once
        $el.append(output);
    });
});
.halfStyle {
  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 */
}

.halfStyle:before { /* creates the top part */
  display: block;
  z-index: 2;
  position: absolute;
  top: 0;
  height: 50%;
  content: attr(data-content); /* dynamic content for the pseudo element */
  overflow: hidden;
  pointer-events: none; /* so the base char is selectable by mouse */
  color: #f00; /* for demo purposes */
  text-shadow: 2px -2px 0px #af0; /* for demo purposes */
}

.halfStyle:after { /* creates the bottom part */
  display: block;
  position: absolute;
  z-index: 1;
  top: 0;
  height: 100%;
  content: attr(data-content); /* dynamic content for the pseudo element */
  overflow: hidden;
  pointer-events: none; /* so the base char is selectable by mouse */
  color: #000; /* for demo purposes */
  text-shadow: 2px 2px 0px #0af; /* for demo purposes */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Single Characters:</p>
<span class="halfStyle" data-content="X">X</span>
<span class="halfStyle" data-content="Y">Y</span>
<span class="halfStyle" data-content="Z">Z</span>
<span class="halfStyle" data-content="A">A</span>

<hr/>
<p>Automated:</p>

<span class="textToHalfStyle">Half-style, please.</span>

JSFiddle demo



- 垂直1/3部件

  • 没有文字阴影:

    halfStyle - Vertical 1/3 Parts - No Text Shadow

  • 文本阴影的可能性为每1/3部分独立:

    halfStyle - Vertical 1/3 Parts - With Text Shadow

// jQuery for automated mode
jQuery(function($) {
    var text, chars, $el, i, output;

    // Iterate over all class occurences
    $('.textToHalfStyle').each(function(idx, el) {
    $el = $(el);
    text = $el.text();
    chars = text.split('');

    // Set the screen-reader text
    $el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');

    // Reset output for appending
    output = '';

    // Iterate over all chars in the text
    for (i = 0; i < chars.length; i++) {
        // Create a styled element for each character and append to container
        output += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';
    }

    // Write to DOM only once
    $el.append(output);
  });
});
.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: #f0f; /* for demo purposes */
    text-shadow: 2px 2px 0px #0af; /* 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: #f00; /* for demo purposes */
    text-shadow: 2px -2px 0px #af0; /* 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: #000; /* for demo purposes */
    text-shadow: 2px 2px 0px #af0; /* for demo purposes */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p>Single Characters:</p>
<span class="halfStyle" data-content="X">X</span>
<span class="halfStyle" data-content="Y">Y</span>
<span class="halfStyle" data-content="Z">Z</span>
<span class="halfStyle" data-content="A">A</span>

<hr/>
<p>Automated:</p>

<span class="textToHalfStyle">Half-style, please.</span>

JSFiddle demo



- 水平1/3部件

  • 没有文字阴影:

    halfStyle - Horizontal 1/3 Parts - No Text Shadow

  • 文本阴影的可能性为每1/3部分独立:

    halfStyle - Horizontal 1/3 Parts - With Text Shadow

// jQuery for automated mode
jQuery(function($) {
    var text, chars, $el, i, output;

    // Iterate over all class occurences
    $('.textToHalfStyle').each(function(idx, el) {
    $el = $(el);
    text = $el.text();
    chars = text.split('');

    // Set the screen-reader text
    $el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');

    // Reset output for appending
    output = '';

    // Iterate over all chars in the text
    for (i = 0; i < chars.length; i++) {
        // Create a styled element for each character and append to container
        output += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';
    }

    // Write to DOM only once
    $el.append(output);
  });
});
.halfStyle { /* base char and also the bottom 1/3 */
  position: relative;
  display: inline-block;
  font-size: 80px; /* or any font size will work */
  color: transparent;
  overflow: hidden;
  white-space: pre; /* to preserve the spaces from collapsing */
  color: #f0f;
  text-shadow: 2px 2px 0px #0af; /* for demo purposes */
}

.halfStyle:before { /* creates the top 1/3 */
  display: block;
  z-index: 2;
  position: absolute;
  top: 0;
  height: 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: #f00; /* for demo purposes */
  text-shadow: 2px -2px 0px #fa0; /* for demo purposes */
}

.halfStyle:after { /* creates the middle 1/3 */
  display: block;
  position: absolute;
  z-index: 1;
  top: 0;
  height: 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: #000; /* for demo purposes */
  text-shadow: 2px 2px 0px #af0; /* for demo purposes */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Single Characters:</p>
<span class="halfStyle" data-content="X">X</span>
<span class="halfStyle" data-content="Y">Y</span>
<span class="halfStyle" data-content="Z">Z</span>
<span class="halfStyle" data-content="A">A</span>

<hr/>
<p>Automated:</p>

<span class="textToHalfStyle">Half-style, please.</span>

JSFiddle demo



-HalfStyle改进由@KevinGranger

halfStyle - KevinGranger

// jQuery for automated mode
jQuery(function($) {
    var text, chars, $el, i, output;

    // Iterate over all class occurences
    $('.textToHalfStyle').each(function(idx, el) {
    $el = $(el);
    text = $el.text();
    chars = text.split('');

    // Set the screen-reader text
    $el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');

    // Reset output for appending
    output = '';

    // Iterate over all chars in the text
    for (i = 0; i < chars.length; i++) {
        // Create a styled element for each character and append to container
        output += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';
    }

    // Write to DOM only once
    $el.append(output);
  });
});
body {
    background-color: black;
}

.textToHalfStyle {
    display: block;
    margin: 200px 0 0 0;
    text-align: center;
}

.halfStyle {
    font-family: 'Libre Baskerville', serif;
    position: relative;
    display: inline-block;
    width: 1;
    font-size: 70px;
    color: black;
    overflow: hidden;
    white-space: pre;
    text-shadow: 1px 2px 0 white;
}

.halfStyle:before {
    display: block;
    z-index: 1;
    position: absolute;
    top: 0;
    width: 50%;
    content: attr(data-content); /* dynamic content for the pseudo element */
    overflow: hidden;
    color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Single Characters:</p>
<span class="halfStyle" data-content="X">X</span>
<span class="halfStyle" data-content="Y">Y</span>
<span class="halfStyle" data-content="Z">Z</span>
<span class="halfStyle" data-content="A">A</span>

<hr/>
<p>Automated:</p>

<span class="textToHalfStyle">Half-style, please.</span>

JSFiddle demo

<小时/>

-PelelingStyle由@SamTremaine

改进HalfStyle

halfStyle - SamTremaine

// jQuery for automated mode
jQuery(function($) {
    var text, chars, $el, i, output;

    // Iterate over all class occurences
    $('.textToHalfStyle').each(function(idx, el) {
    $el = $(el);
    text = $el.text();
    chars = text.split('');

    // Set the screen-reader text
    $el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');

    // Reset output for appending
    output = '';

    // Iterate over all chars in the text
    for (i = 0; i < chars.length; i++) {
        // Create a styled element for each character and append to container
        output += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';
    }

    // Write to DOM only once
    $el.append(output);
  });
});
.halfStyle {
    position: relative;
    display: inline-block;
    font-size: 68px;
    color: rgba(0, 0, 0, 0.8);
    overflow: hidden;
    white-space: pre;
    transform: rotate(4deg);
    text-shadow: 2px 1px 3px rgba(0, 0, 0, 0.3);
}

.halfStyle:before { /* creates the left part */
    display: block;
    z-index: 1;
    position: absolute;
    top: -0.5px;
    left: -3px;
    width: 100%;
    content: attr(data-content);
    overflow: hidden;
    pointer-events: none;
    color: #FFF;
    transform: rotate(-4deg);
    text-shadow: 0px 0px 1px #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Single Characters:</p>
<span class="halfStyle" data-content="X">X</span>
<span class="halfStyle" data-content="Y">Y</span>
<span class="halfStyle" data-content="Z">Z</span>
<span class="halfStyle" data-content="A">A</span>

<hr/>
<p>Automated:</p>

<span class="textToHalfStyle">Half-style, please.</span>

JSFiddle demosamtremaine.co.uk

<小时/>

第4部分:准备生产

可以在同一页面上的所需元素上使用自定义的不同半风格样式集。 您可以定义多个样式集并告诉插件使用哪个样式集。

该插件在目标data-halfstyle="[-CustomClassName-]"元素上使用数据属性.textToHalfStyle,并自动进行所有必要的更改。

因此,只需在包含文本的元素上添加textToHalfStyle类和数据属性data-halfstyle="[-CustomClassName-]"。该插件将完成剩下的工作。

halfStyle - Multiple on Same Page

CSS样式集的类定义也与上面提到的[-CustomClassName-]部分匹配,并且链接到.halfStyle,因此我们将.halfStyle.[-CustomClassName-]

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 !important;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>';
        }

        // Write to DOM only once
        $halfstyle_el.append(halfstyle_output);
    });
});
/* start half-style hs-base */

.halfStyle.hs-base {
    position: relative;
    display: inline-block;
    font-size: 80px; /* or any font size will work */
    overflow: hidden;
    white-space: pre; /* to preserve the spaces from collapsing */
    color: #000; /* for demo purposes */
}

.halfStyle.hs-base:before {
    display: block;
    z-index: 1;
    position: absolute;
    top: 0;
    width: 50%;
    content: attr(data-content); /* dynamic content for the pseudo element */
    pointer-events: none; /* so the base char is selectable by mouse */
    overflow: hidden;
    color: #f00; /* for demo purposes */
}

/* end half-style hs-base */


/* start half-style hs-horizontal-third */

.halfStyle.hs-horizontal-third { /* base char and also the bottom 1/3 */
    position: relative;
    display: inline-block;
    font-size: 80px; /* or any font size will work */
    color: transparent;
    overflow: hidden;
    white-space: pre; /* to preserve the spaces from collapsing */
    color: #f0f;
    text-shadow: 2px 2px 0px #0af; /* for demo purposes */
}

.halfStyle.hs-horizontal-third:before { /* creates the top 1/3 */
    display: block;
    z-index: 2;
    position: absolute;
    top: 0;
    height: 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: #f00; /* for demo purposes */
    text-shadow: 2px -2px 0px #fa0; /* for demo purposes */
}

.halfStyle.hs-horizontal-third:after { /* creates the middle 1/3 */
    display: block;
    position: absolute;
    z-index: 1;
    top: 0;
    height: 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: #000; /* for demo purposes */
    text-shadow: 2px 2px 0px #af0; /* for demo purposes */
}

/* end half-style hs-horizontal-third */


/* start half-style hs-PeelingStyle, by user SamTremaine on Stackoverflow.com */

.halfStyle.hs-PeelingStyle {
  position: relative;
  display: inline-block;
  font-size: 68px;
  color: rgba(0, 0, 0, 0.8);
  overflow: hidden;
  white-space: pre;
  transform: rotate(4deg);
  text-shadow: 2px 1px 3px rgba(0, 0, 0, 0.3);
}

.halfStyle.hs-PeelingStyle:before { /* creates the left part */
  display: block;
  z-index: 1;
  position: absolute;
  top: -0.5px;
  left: -3px;
  width: 100%;
  content: attr(data-content);
  overflow: hidden;
  pointer-events: none;
  color: #FFF;
  transform: rotate(-4deg);
  text-shadow: 0px 0px 1px #000;
}

/* end half-style hs-PeelingStyle */


/* start half-style hs-KevinGranger, by user KevinGranger on StackOverflow.com*/

.textToHalfStyle.hs-KevinGranger {
  display: block;
  margin: 200px 0 0 0;
  text-align: center;
}

.halfStyle.hs-KevinGranger {
  font-family: 'Libre Baskerville', serif;
  position: relative;
  display: inline-block;
  width: 1;
  font-size: 70px;
  color: black;
  overflow: hidden;
  white-space: pre;
  text-shadow: 1px 2px 0 white;
}

.halfStyle.hs-KevinGranger:before {
  display: block;
  z-index: 1;
  position: absolute;
  top: 0;
  width: 50%;
  content: attr(data-content); /* dynamic content for the pseudo element */
  overflow: hidden;
  color: white;
}

/* end half-style hs-KevinGranger
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>
    <span class="textToHalfStyle" data-halfstyle="hs-base">Half-style, please.</span>
</p>
<p>
    <span class="textToHalfStyle" data-halfstyle="hs-horizontal-third">Half-style, please.</span>
</p>
<p>
    <span class="textToHalfStyle" data-halfstyle="hs-PeelingStyle">Half-style, please.</span>
</p>
<p style="background-color:#000;">
    <span class="textToHalfStyle" data-halfstyle="hs-KevinGranger">Half-style, please.</span>
</p>

JSFiddle demo

答案 1 :(得分:468)

enter image description here


我刚刚完成了插件的开发,每个人都可以使用它!希望你会喜欢它。

GitHub上查看项目 - 查看项目Website(所以你可以看到所有的分割风格)

用法

首先,确保包含jQuery库。获取最新jQuery版本的最佳方法是使用以下命令更新头标记:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>

下载文件后,请确保将它们包含在项目中:

<link rel="stylesheet" type="text/css" href="css/splitchar.css">
<script type="text/javascript" src="js/splitchar.js"></script>

标记

您所要做的就是将类splitchar取消,然后将所需的样式添加到包装文本的元素中。 e.g

<h1 class="splitchar horizontal">Splitchar</h1>

完成所有这些后,只需确保在文档就绪文件中调用jQuery函数,如下所示:

$(".splitchar").splitchar();

定制

为了使文本看起来完全符合您的要求,您只需要按照以下方式应用您的设计:

.horizontal { /* Base CSS - e.g font-size */ }
.horizontal:before { /* CSS for the left half */ }
.horizontal:after { /* CSS for the right half */ }


而已!现在你已经设置了Splitchar插件。有关它的更多信息,请访问http://razvanbalosin.com/Splitchar.js/

答案 2 :(得分:213)

  

编辑(2017年10月):现在,每个主要浏览器都支持background-clip或更确切background-image optionsCanIUse

是的,您只能使用一个字符而且只能使用CSS。

仅限Webkit(和Chrome):

http://jsbin.com/rexoyice/1/

&#13;
&#13;
h1 {
  display: inline-block;
  margin: 0; /* for demo snippet */
  line-height: 1em; /* for demo snippet */
  font-family: helvetica, arial, sans-serif;
  font-weight: bold;
  font-size: 300px;
  background: linear-gradient(to right, #7db9e8 50%,#1e5799 50%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
&#13;
<h1>X</h1>
&#13;
&#13;
&#13;

从视觉上看,所有使用两个字符的示例(无论是通过JS,CSS伪元素还是只是HTML)看起来都很好,但请注意,所有这些都会向DOM添加可能导致可访问性的内容 - 以及文本选择/剪切/粘贴问题。

答案 3 :(得分:151)

Example


JSFiddle DEMO

我们只使用CSS伪选择器来做!

此技术适用于动态生成的内容以及不同的字体大小和宽度。

<强> HTML:

<div class='split-color'>Two is better than one.</div>

<强> 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;
}

要包装动态生成的字符串,可以使用如下函数:

// 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);
}

答案 4 :(得分:93)

这可能是无关紧要的,也许不是,但不久前,我创建了一个jQuery函数,它可以做同样的事情,但是是水平的。

我打电话给他&#34; Strippex&#34;对于&#39; stripe&#39; +&#39; text&#39;,演示:http://cdpn.io/FcIBg

我并不是说这是任何问题的解决方案,但我已经尝试将css应用于角色的一半,但是水平,所以这个想法是一样的,实现可能是可怕的,但它的工作原理

啊,最重要的是,我很开心创造它!

enter image description here

答案 5 :(得分:70)

这是一个丑陋的画布实现。我尝试了这个解决方案,但结果比我预期的要糟糕,所以无论如何都是这样。

Canvas example

&#13;
&#13;
        $("div").each(function(){
            var CHARS = $(this).text().split('');
            $(this).html("");
            $.each(CHARS,function(index, char){
                var canvas = $("<canvas />")
                        .css("width", "40px")
                        .css("height", "40px")
                        .get(0);
                $("div").append(canvas);
                var ctx = canvas.getContext("2d");
                var gradient = ctx.createLinearGradient(0, 0, 130, 0);
                gradient.addColorStop("0", "blue");
                gradient.addColorStop("0.5", "blue");
                gradient.addColorStop("0.51", "red");
                gradient.addColorStop("1.0", "red");
                ctx.font = '130pt Calibri';
                ctx.fillStyle = gradient;
                ctx.fillText(char, 10, 130);
            });
        });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Example Text</div>
&#13;
&#13;
&#13;

答案 6 :(得分:68)

如果你对此感兴趣,那么Lucas Bebber的Glitch就是一个非常相似且超酷的效果:

enter image description here

使用简单的SASS Mixin创建,例如

.example-one {
  font-size: 100px;
  @include textGlitch("example-one", 17, white, black, red, blue, 450, 115);
}

Chris Coyer's CSS TricksLucas Bebber's Codepen page

的更多详情

答案 7 :(得分:59)

我最近可以得到:

$(function(){
  $('span').width($('span').width()/2);
  $('span:nth-child(2)').css('text-indent', -$('span').width());
});
body{
  font-family: arial;
}
span{
  display: inline-block;
  overflow: hidden;
}
span:nth-child(2){
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>X</span><span>X</span>

演示:http://jsfiddle.net/9wxfY/2/

这是一个只使用一个范围的版本:http://jsfiddle.net/9wxfY/4/

答案 8 :(得分:53)

Enter image description here

我刚刚使用@ Arbel的解决方案:

&#13;
&#13;
var textToHalfStyle = $('.textToHalfStyle').text();
var textToHalfStyleChars = textToHalfStyle.split('');
$('.textToHalfStyle').html('');
$.each(textToHalfStyleChars, function(i,v){
    $('.textToHalfStyle').append('<span class="halfStyle" data-content="' + v + '">' + v + '</span>');
});
&#13;
body{
    background-color: black;
}
.textToHalfStyle{
    display:block;
    margin: 200px 0 0 0;
    text-align:center;
}
.halfStyle {
    font-family: 'Libre Baskerville', serif;
    position:relative;
    display:inline-block;
    width:1;
    font-size:70px;
    color: black;
    overflow:hidden;
    white-space: pre;
    text-shadow: 1px 2px 0 white;
}
.halfStyle:before {
    display:block;
    z-index:1;
    position:absolute;
    top:0;
    width: 50%;
    content: attr(data-content); /* dynamic content for the pseudo element */
    overflow:hidden;
    color: white;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<span class="textToHalfStyle">Dr. Jekyll and M. Hide</span>
&#13;
&#13;
&#13;

答案 9 :(得分:42)

另一种仅限CSS的解决方案(如果您不想编写特定于字母的CSS,则需要数据属性)。这个更全面地工作(测试IE 9/10,Chrome最新和FF最新)

span {
  position: relative;
  color: rgba(50,50,200,0.5);
}

span:before {
  content: attr(data-char);
  position: absolute;
  width: 50%;
  overflow: hidden;
  color: rgb(50,50,200);
}
<span data-char="X">X</span>

答案 10 :(得分:36)

有限的CSS和jQuery解决方案

我不确定这个解决方案有多优雅,但它会将所有内容完全切成两半:http://jsfiddle.net/9wxfY/11/

否则,我已经为您创建了一个很好的解决方案......您需要做的就是为您的HTML提供:

从2016年6月13日开始,请查看最新,最准确的编辑内容:http://jsfiddle.net/9wxfY/43/

至于CSS,它非常有限......你只需要将它应用到:nth-child(even)

&#13;
&#13;
$(function(){
  var $hc = $('.half-color');
  var str = $hc.text();
  $hc.html("");

  var i = 0;
  var chars;
  var dupText;

  while(i < str.length){
    chars = str[i];
    if(chars == " ") chars = "&nbsp;";
    dupText = "<span>" + chars + "</span>";

    var firstHalf = $(dupText);
    var secondHalf = $(dupText);

    $hc.append(firstHalf)
    $hc.append(secondHalf)

    var width = firstHalf.width()/2;

    firstHalf.width(width);
    secondHalf.css('text-indent', -width);

    i++;
  }
});
&#13;
.half-color span{
  font-size: 2em;
  display: inline-block;
  overflow: hidden;
}
.half-color span:nth-child(even){
  color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="half-color">This is a sentence</div>
&#13;
&#13;
&#13;

答案 11 :(得分:29)

.halfStyle {
    position:relative;
    display:inline-block;
    font-size:68px; /* or any font size will work */
    color: rgba(0,0,0,0.8); /* or transparent, any color */
    overflow:hidden;
    white-space: pre; /* to preserve the spaces from collapsing */
    transform:rotate(4deg);
    -webkit-transform:rotate(4deg);
    text-shadow:2px 1px 3px rgba(0,0,0,0.3);
}
.halfStyle:before {
    display:block;
    z-index:1;
    position:absolute;
    top:-0.5px;
    left:-3px;
    width: 100%;
    content: attr(data-content); /* dynamic content for the pseudo element */
    overflow:hidden;
    color: white;
    transform:rotate(-4deg);
    -webkit-transform:rotate(-4deg);
    text-shadow:0 0 1px black;

}

http://experimental.samtremaine.co.uk/half-style/

你可以将这段代码撬开来做各种有趣的事情 - 这只是我的同事和我昨晚想出来的一个实现。

答案 12 :(得分:24)

一个利用background-clip: text支持的优秀WebKit解决方案:http://jsfiddle.net/sandro_paganotti/wLkVt/

span{
   font-size: 100px;
   background: linear-gradient(to right, black, black 50%, grey 50%, grey);
   -webkit-background-clip: text;
   -webkit-text-fill-color: transparent;
}

答案 13 :(得分:22)

FWIW,这是我对此的看法:http://codepen.io/ricardozea/pen/uFbts/

几点说明:

  • 我这样做的主要原因是为了测试自己,看看我是否能够在为OP提供有意义的答案的同时完成一半角色的造型。

  • 我知道这不是一个理想的或最具扩展性的解决方案,而且这里的人们提出的解决方案对于“真实世界”场景来说要好得多。

  • 我创建的CSS代码基于我想到的第一个想法和我个人对问题的处理方法。

  • 我的解决方案仅适用于对称字符,如X,A,O,M。**它不适用于不对称字符,如B,C,F,K或小写字母。

    < / LI>
  • **然而,这种方法会产生非常有趣的“形状”,具有不对称的字符。尝试在CSS中将X更改为K或小写字母,如 h p :)

<强> HTML

<span class="half-letter"></span>

<强> SCSS

.half-character { 
  display: inline-block;
  font: bold 350px/.8 Arial;
  position: relative;

  &:before, &:after {
    content: 'X'; //Change character here
    display: inline-block;
    width: 50%;
    overflow: hidden;
    color: #7db9e8;
  }
  &:after {
    position: absolute;
    top: 0;
    left: 50%;
    color: #1e5799;
    transform: rotateY(-180deg);
  }
}

答案 14 :(得分:20)

对于较短的文字,这样的事情怎么样?

如果您使用循环执行某些操作,使用JavaScript重复这些字符,它甚至可以用于更长的文本。无论如何,结果是这样的:

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

p.char {
  position: relative;
  display: inline-block;
  font-size: 60px;
  color: red;
}

p.char:before {
  position: absolute;
  content: attr(char);
  width: 50%;
  overflow: hidden;
  color: black;
}
<p class="char" char="S">S</p>
<p class="char" char="t">t</p>
<p class="char" char="a">a</p>
<p class="char" char="c">c</p>
<p class="char" char="k">k</p>
<p class="char" char="o">o</p>
<p class="char" char="v">v</p>
<p class="char" char="e">e</p>
<p class="char" char="r">r</p>
<p class="char" char="f">f</p>
<p class="char" char="l">l</p>
<p class="char" char="o">o</p>
<p class="char" char="w">w</p>

答案 15 :(得分:16)

如果您愿意,也可以使用SVG执行此操作:

&#13;
&#13;
var title = document.querySelector('h1'),
    text = title.innerHTML,
    svgTemplate = document.querySelector('svg'),
    charStyle = svgTemplate.querySelector('#text');

svgTemplate.style.display = 'block';

var space = 0;

for (var i = 0; i < text.length; i++) {
  var x = charStyle.cloneNode();
  x.textContent = text[i];
  svgTemplate.appendChild(x);
  x.setAttribute('x', space);
  space += x.clientWidth || 15;
}

title.innerHTML = '';
title.appendChild(svgTemplate);
&#13;
<svg style="display: none; height: 100px; width: 100%" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">
    <defs id="FooDefs">
        <linearGradient id="MyGradient" x1="0%" y1="0%" x2="100%" y2="0%">
            <stop offset="50%" stop-color="blue" />
            <stop offset="50%" stop-color="red" />
        </linearGradient>
    </defs>
    <text y="50%" id="text" style="font-size: 72px; fill: url(#MyGradient)"></text>
</svg>

<h1>This is not a solution X</h1>
&#13;
&#13;
&#13;

http://codepen.io/nicbell/pen/jGcbq

答案 16 :(得分:14)

只需使用CSS form f = new form();选择器和:before即可实现此目的。

content property value
.halfed, .halfed1 {
  float: left;
}

.halfed, .halfed1 {
  font-family: arial;
  font-size: 300px;
  font-weight: bolder;
  width: 200px;
  height: 300px;
  position: relative; /* To help hold the content value within */
  overflow: hidden;
  color: #000;
}




.halfed:before, .halfed1:before   {
  width: 50%; /* How much we'd like to show */
  overflow: hidden; /* Hide what goes beyond our dimension */  
  content: 'X'; /* Halfed character */
  height: 100%;
  position: absolute;
  color: #28507D;

}



/* For Horizontal cut off */ 

.halfed1:before   {
  width: 100%;
  height: 55%;
  
}

>> See on jsFiddle

答案 17 :(得分:7)

您可以使用以下代码。在此示例中,我使用了h1标记并添加了一个属性data-title-text="Display Text",该属性将在h1标记文本元素上显示不同的颜色文本,从而生成半颜色文本,如下例所示< / p>

enter image description here

&#13;
&#13;
body {
  text-align: center;
  margin: 0;
}

h1 {
  color: #111;
  font-family: arial;
  position: relative;
  font-family: 'Oswald', sans-serif;
  display: inline-block;
  font-size: 2.5em;
}

h1::after {
  content: attr(data-title-text);
  color: #e5554e;
  position: absolute;
  left: 0;
  top: 0;
  clip: rect(0, 1000px, 30px, 0);
}
&#13;
<h1 data-title-text="Display Text">Display Text</h1>
&#13;
&#13;
&#13;

答案 18 :(得分:3)

仅用于历史记录!

我为自己5到6年前的工作提出了一个解决方案,即Gradext(纯JavaScript和纯CSS,无依赖项)。

技术上的解释是您可以创建这样的元素:

<span>A</span>

现在,如果要在文本上进行渐变,则需要创建一些多层,每个层分别进行特殊着色,并且创建的光谱将说明渐变效果。

例如,看看这是<span>内的 lorem 一词,它将引起水平渐变效果(check the examples):

 <span data-i="0" style="color: rgb(153, 51, 34);">L</span>
 <span data-i="1" style="color: rgb(154, 52, 35);">o</span>
 <span data-i="2" style="color: rgb(155, 53, 36);">r</span>
 <span data-i="3" style="color: rgb(156, 55, 38);">e</span>
 <span data-i="4" style="color: rgb(157, 56, 39);">m</span>

您也可以在很长一段很长的时间内继续执行此模式。

enter image description here

但是!

如果要在文本上创建垂直渐变效果怎么办?

然后有另一个解决方案可能会有所帮助。我将详细描述。

再次假设我们的第一个<span>。但是内容不应该单独是字母;内容应该是全文,现在我们要一次又一次地复制相同的‍ <span>(跨度数将定义渐变的质量,更大的跨度,更好的结果,但性能较差)。看看这个:

<span data-i="6" style="color: rgb(81, 165, 39); overflow: hidden; height: 11.2px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>
<span data-i="7" style="color: rgb(89, 174, 48); overflow: hidden; height: 12.8px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>
<span data-i="8" style="color: rgb(97, 183, 58); overflow: hidden; height: 14.4px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>
<span data-i="9" style="color: rgb(105, 192, 68); overflow: hidden; height: 16px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>
<span data-i="10" style="color: rgb(113, 201, 78); overflow: hidden; height: 17.6px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>
<span data-i="11" style="color: rgb(121, 210, 88); overflow: hidden; height: 19.2px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>

enter image description here

再次,但是!

如果要使这些渐变效果移动并从中创建动画怎么办?

嗯,还有另一种解决方案。您绝对应该检查animation: true甚至.hoverable()方法,这将导致基于光标位置的渐变开始! (听起来很酷xD)

enter image description here

这就是我们在文本上创建渐变(线性或径向)的方式。如果您喜欢这个主意或想进一步了解它,则应检查提供的链接。


也许这不是最好的选择,也许不是执行此操作的最佳方法,但是它将为创造令人兴奋和令人愉悦的动画打开一些空间,以激励其他人寻求更好的解决方案。

它将允许您在文本上使用渐变样式,甚至IE8也支持!

Here you can find a working live demo,原始存储库为here on GitHub as well, open source,准备进行一些更新(:D)

这是我第一次(是的,五年后,您没听错),我在互联网上的任何地方都提到了这个存储库,对此我感到很兴奋!

答案 19 :(得分:1)

enter image description here

这是针对整行文本的仅 CSS 解决方案,而不仅仅是字符元素。

div {
    position: relative;
    top: 2em;
    height: 2em;
    text-transform: full-width;
}

div:before,
div:after {
    content: attr(data-content);
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}

div:after {
    color: red;
    /* mask for a single character. By repeating this mask, all the string becomes masked */
    -webkit-mask-image: linear-gradient(to right, transparent 0, transparent .5em, white .5em, white 1em);
    -webkit-mask-repeat: repeat-x;  /* repeat the mask towards the right */
    -webkit-mask-size: 1em;         /* relative width of a single character */ 
    
    /* non-vendor mask settings */
    mask-image: linear-gradient(to right, transparent 0, transparent .5em, white .5em, white 1em);
    mask-repeat: repeat-x;
    mask-size: 1em;
}


/* demo purposes */
input[name="fontSize"]:first-of-type:checked ~ div {
    font-size: 1em;
}

input[name="fontSize"]:first-of-type + input:checked ~ div {
    font-size: 2em;
}

input[name="fontSize"]:first-of-type + input + input:checked ~ div {
    font-size: 3em;
}
Font-size:
  <input type="radio" name="fontSize" value="1em">
  <input type="radio" name="fontSize" value="2em" checked>
  <input type="radio" name="fontSize" value="3em">

  <div data-content="A CSS only solution..."></div>
  <div data-content="Try it on Firefox!"></div>

这个想法是为每个字符应用一个水平 CSS 掩码,隐藏它的前半部分 [0 - 0.5em] 并显示后半部分 [0.5em - 1em]。

掩码的宽度为 mask-size: 1em 以匹配字符串中第一个字符的宽度。 通过使用 mask-repeat: repeat-x,相同的掩码应用于第二个、第三个字符等。

我认为使用字体monospace可以解决使用等宽字母的问题,但我错了。 相反,我使用 text-transform: full-width 解决了这个问题,不幸的是,我相信只有 Firefox 支持。

使用相对单位 em 允许设计根据 font-size 放大/缩小。

适用于所有浏览器的原生 JavaScript 解决方案

如果无法选择 Firefox,则使用此脚本进行救援。

它的工作原理是为每个字符插入一个子 span。在每个 span 内,一个非重复的 CSS 掩码放置在 [0% - 50%] 和 [50% - 100%] 字母宽度(即 span 元素的宽度)之间。

这样我们就不再有使用等宽字符的限制了。

const
    dataElement = document.getElementById("data"),
    content = dataElement.textContent,
    zoom = function (fontSize) {
        dataElement.style['font-size'] = fontSize + 'em';           
    };

while (dataElement.firstChild) {
    dataElement.firstChild.remove()
}
for(var i = 0; i < content.length; ++i) {
    const
        spanElem = document.createElement('span'),
        ch = content[i];    
    spanElem.setAttribute('data-ch', ch);
    spanElem.appendChild(document.createTextNode(ch === ' ' ? '\u00A0' : ch));
    data.appendChild(spanElem);
}
#data {
    position: relative;
    top: 2em;
    height: 2em;
    font-size: 2em;
}

#data span {
    display: inline-block;
    position: relative;
    color: transparent;
}

#data span:before,
#data span:after {
    content: attr(data-ch);
    display: inline-block;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    text-align: center;
    color: initial;
}

#data span:after {
    color: red;
    -webkit-mask-image: linear-gradient(to right, transparent 0, transparent 50%, white 50%, white 100%);
    mask-image: linear-gradient(to right, transparent 0, transparent 50%, white 50%, white 100%);
}
Font-size:
<input type="range" min=1 max=4 step=0.05 value=2 oninput="zoom(this.value)" onchange="zoom(this.value)">

<div id="data">A Fallback Solution...For all browsers</div>