如何在html元素文本中为特定字母着色? [英] How can I color specific letters in html element text?

查看:89
本文介绍了如何在html元素文本中为特定字母着色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些 span ,里面有一些单词,比如

I have some span with some words in it, like

        <span id="phrase">Here are some words</span>

我需要为所有'e'着色字符为红色。

I need to color all the 'e' characters red.

我想要获取 span.innerText属性,从span元素中删除文本节点并添加内部(或替代)更多的跨度,并给他们必要的风格。

I think of taking the span.innerText property, remove text node from span element and add some more spans inside (or instead), and give them necessary style.

这是唯一的方式,还是可以以更优雅的方式解决?

Is it the only way, or it could be solved in a more elegant way?

推荐答案

你一定可以用javascript来做:

You can surely do it with javascript:

var span = document.getElementById('phrase'),
    text = span.innerHTML.split('').map(function(el) {
        return '<span class="char-' + el.toLowerCase() + '">' + el + '</span>';
    }).join('');
  
span.innerHTML = text;

.char-e {
    color: red;
}

<span id="phrase">Here are some words</span>

为方便起见使用具有相应类名的跨度包装每个字符,这样可以轻松分配各个样式。

For convenience it wraps each character with a span with corresponding class name, which makes it easy to assign individual styles.

警告:但是我不建议这样做这有大文本,因为上面的代码替换 innerHTML 如果它包含其他嵌套元素,它可以破坏你的HTML。但是对于只有文本的小标题,这不会有问题。

Warning: However I would not recommend doing this with large texts because the code above replaces innerHTML it can break your HTML if it contains other nested elements. But for small titles with only text this is not going to be a problem.

如果你想使用更复杂的HTML标记(带子元素),那么函数需要被改进以递归地处理子项目文本内容。

If you want to work with more complex HTML markup (with children elements) the function needs to be improved to work recursively on child items text content.

这篇关于如何在html元素文本中为特定字母着色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆