使用 CSS 设置某些字符的样式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16091469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 22:31:18  来源:igfitidea点击:

Style certain characters with CSS

css

提问by Svish

I'm assuming it's not possible, but just in case it is or someone has a nice trick up their sleeves, is there a way to target certain characters using CSS?

我假设这是不可能的,但以防万一或者有人有一个很好的伎俩,有没有办法使用 CSS 定位某些字符?

For example make all letters zin paragraphs red, or in my particular case set vertical-align:supon all 7in elements marked with the class chord.

例如,将z段落中的所有字母设置为红色,或者在我的特定情况下将vertical-align:sup所有7标记为 class 的元素设置为红色chord

采纳答案by mattytommo

That's not possible in CSS. Your only option would be first-letterand that's not going to cut it. Either use JavaScript or (as you stated in your comments), your server-side language.

这在 CSS 中是不可能的。你唯一的选择是first-letter,这不会削减它。使用 JavaScript 或(如您在评论中所述)您的服务器端语言。

回答by ncubica

Hi I know you said in CSS but as everybody told you, you can't, this is a javascript solution, just my 2 cents.

嗨,我知道你在 CSS 中说过,但正如每个人告诉你的,你不能,这是一个 javascript 解决方案,只有我的 2 美分。

best...

最好的事物...

JSFiddle

JSFiddle

css

css

span.highlight{
   background:#F60;
    padding:5px;
    display:inline-block;
    color:#FFF;
}

p{
   font-family:Verdana;   
}

html

html

<p>
    Let's go Zapata let's do it for the revolution, Zapatistas!!!   
</p>

javascript

javascript

jQuery.fn.highlight = function (str, className) {    
    var regex = new RegExp(str, "gi");

    return this.each(function () {
        this.innerHTML = this.innerHTML.replace(regex, function(matched) {return "<span class=\"" + className + "\">" + matched + "</span>";});
    });
};

$("p").highlight("Z","highlight");

Resultenter image description here

结果在此处输入图片说明

回答by Boy Buysman

The only way to do it in CSS is to wrap them in a span and give the span a class. Then target all spans with that class.

在 CSS 中做到这一点的唯一方法是将它们包装在一个跨度中并为该跨度提供一个类。然后针对该类的所有跨度。

回答by ratigumashvili

As far as I understand it only works with regular characters/letters. For example: what if we want to highlight all asterisk (\u002A) symbols on page. Tried $("p").highlight("u\(u002A)","highlight");in js and inserted &#42;in html but it did not worked.

据我了解,它仅适用于常规字符/字母。例如:如果我们想突出显示页面上的所有星号 (\u002A) 符号怎么办。$("p").highlight("u\(u002A)","highlight");在 js 中尝试 并插入&#42;到 html 中,但没有奏效。