Html 如何使用 CSS 为容器中的特定单词着色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23737776/
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
How to color specific word in a container using CSS
提问by nicael
Suppose I have a container:
假设我有一个容器:
<div id="container"> This is a red apple </div>
How to color a word "red" with red color? Something like (pseudocode)
如何用红色给单词“red”上色?类似(伪代码)
#container:[word="red"]{
color:red;
}
Is it possible to do this in pure CSS without introducing JavaScript or modifying the existing HTML?
是否可以在不引入 JavaScript 或修改现有 HTML 的情况下在纯 CSS 中执行此操作?
采纳答案by agrm
Not to prove a point, but to answer your question - this ispossible in CSS without JS: Example
不是为了证明一个观点,而是为了回答你的问题——这在没有 JS 的 CSS 中是可能的:示例
In short: we set a black background color for text color and a red background image for the specific red string. We remove the original text fill using -webkit-text-fill-color
. The background is clipped to the text outline using -webkit-background-clip: text;
and the red image is sized and positioned over whatever text string we want to color.
简而言之:我们为文本颜色设置黑色背景颜色,为特定红色字符串设置红色背景图像。我们使用 删除原始文本填充-webkit-text-fill-color
。背景被剪裁到文本轮廓使用-webkit-background-clip: text;
,红色图像的大小和位置在我们想要着色的任何文本字符串上。
Please note:I would never recommend using this for any live website. This works in webkit onlyas it's based on non-standard wekbit-specific CSS rules. And the color is not really bound to the colored text string - it's completely static.
请注意:我永远不会建议在任何实时网站上使用它。这仅适用于webkit,因为它基于非标准的 wekbit 特定 CSS 规则。并且颜色并没有真正绑定到彩色文本字符串 - 它是完全静态的。
Edit:Here's the CSS:
编辑:这是CSS:
#container {
-webkit-text-fill-color: transparent;
-webkit-background-clip: text;
background-size: 1.5em 1em;
background-repeat: no-repeat;
background-position: 3.4em 0;
background-color: #000;
background-image: url(data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCAABAAEDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD5rooor8DP9oD/2Q==);
}
回答by Ali Gajani
Background
背景
This is a Vanilla JavaScript solution because it ain't possible with CSS. Not joking, read the specification.You can match on an element, the name of an attribute in the element, and the value of a named attribute in an element. I don't see anything for matching content within an elementthough.
这是一个 Vanilla JavaScript 解决方案,因为它无法使用 CSS。不是开玩笑,请阅读规范。您可以匹配元素、元素中属性的名称以及元素中命名属性的值。但是,我没有看到任何与元素中的内容匹配的内容。
Introduction
介绍
Here's my shot at it. I am sure there is a sleeker way, but this is the gist of how it would start off as. Also, since there are a finite number of colors that you will want to colorify, it's nice to use a bunch of if
statements like I have.
这是我的尝试。我相信有一种更时尚的方式,但这是它如何开始的要点。此外,由于您想要着色的颜色数量有限,因此使用if
像我这样的一堆语句是很好的。
A better technique of course would be to do it more programmatically by building a color dictionary and hence make the code organized. But this works, and it's Vanilla JS. Apparently, I didn't have expertise in Regex, so I am sure a few lines are unnecessary.
当然,更好的技术是通过构建颜色字典以更具编程方式进行操作,从而使代码井井有条。但这有效,而且是 Vanilla JS。显然,我没有正则表达式方面的专业知识,所以我确信几行是不必要的。
Features
特征
- Works for multiple color occurrences
- Works for multiple colors as visible
- 适用于多种颜色出现
- 适用于多种颜色可见
http://jsfiddle.net/TB62H/5/
http://jsfiddle.net/TB62H/5/
var text = document.getElementById("content");
var str = text.innerHTML,
reg = /red|blue|green|orange/ig; //g is to replace all occurances
//fixing a bit
var toStr = String(reg);
var color = (toStr.replace('\/g', '|')).substring(1);
//split it baby
var colors = color.split("|");
if (colors.indexOf("red") > -1) {
str = str.replace(/red/g, '<span style="color:red;">red</span>');
}
if (colors.indexOf("blue") > -1) {
str = str.replace(/blue/g, '<span style="color:blue;">blue</span>');
}
if (colors.indexOf("green") > -1) {
str = str.replace(/green/g, '<span style="color:green;">green</span>');
}
if (colors.indexOf("orange") > -1) {
str = str.replace(/orange/g, '<span style="color:orange;">orange</span>');
}
document.getElementById("updated").innerHTML = str;
Results
结果
回答by abir_maiti
Sadly CSS does not have any selector right now to achieve what you need. You have to use JavaScript or Server Side Scripting to achieve what you want.
遗憾的是,CSS 现在没有任何选择器来实现您的需求。您必须使用 JavaScript 或服务器端脚本来实现您想要的。
回答by mfirdaus
Now if you allow me to use just a bitof javascript, and perhaps the caveat that I have no idea how well this will scale, might break a lot of CSS, and the implementation is a bit shoddy. That said, I think we can simply give css a bit of a hand by rewriting the HTML.
现在,如果您允许我只使用一点javascript,也许需要注意的是,我不知道这将如何扩展,可能会破坏很多 CSS,并且实现有点粗制滥造。也就是说,我认为我们可以通过重写 HTML 来简单地给 css 一些帮助。
As you know we can add spans around the words and we can select that. But instead of just selecting the chosen one and attaching the style information, we span all the words. And attach the word as an value to the attribute "word". With the help of a way to get all the textNodes
, it might look something like
如您所知,我们可以在单词周围添加跨度,然后我们可以选择它。但不是仅仅选择所选择的一个并附加样式信息,我们跨越了所有的词。并将单词作为值附加到属性“单词”。借助一种获取所有内容的方法textNodes
,它可能看起来像
//adapted from https://stackoverflow.com/a/10730777/1480215
function makeHighlightable(){
var n, a=[], walk=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT,null,false);
while(n=walk.nextNode()) a.push(n);
for(var i=0;i<a.length;i++){
var newSpan=document.createElement("span")
var words=a[i].nodeValue.replace(/[\r\n]/g,"").split(' ');
for(var j=0;j<words.length;j++){
var escapedWord=words[j].replace(/[^a-zA-Z0-9-']/g,'').toLowerCase()
words[j]='<span word="'+escapedWord+'">'+words[j]+'</span>'
}
words=words.join(" ")
newSpan.innerHTML=words
a[i].parentNode.replaceChild(newSpan,a[i])
}
}
makeHighlightable()
With that in place, you can now do
有了这个,你现在可以做
#container [word=red]{ /* space instead of : */
color:#F00;
}
and it mightpossibly work.
它可能会起作用。
回答by miguel-svq
Simple but anyway RIGHT answer: NO.
简单但无论如何 正确答案:否。
Please, don't be rude with others in your comments, they took time to read your question, think about how they would solve such a problem, write an answer (or a comment) and... help YOU... they don't deserve be treated in a rude way.
请不要在您的评论中对他人无礼,他们花时间阅读您的问题,思考他们将如何解决这样的问题,写下答案(或评论)并...帮助您...他们不不应该受到粗鲁的对待。
Best regards and good look.
最好的问候和良好的外观。
Miguel.
米格尔。
BTW: check Wrap certain word with <span> using jqueryand http://forum.jquery.com/topic/wrapping-specific-words-inside-span-elements
顺便说一句:使用 jquery和http://forum.jquery.com/topic/wrapping-specific-words-inside-span-elements检查用 <span> 包裹某些单词
回答by Sander Visser
If you don't want to add html/javascript the simpel answer is NO you can't
如果您不想添加 html/javascript,那么简单的答案是否定的,您不能
Take a look at the following specification http://www.w3.org/TR/css3-selectors/#selectors
看看下面的规范 http://www.w3.org/TR/css3-selectors/#selectors
That are all available selectors for CSS3 and therefor it's simply impossible, and that's your answer.
这些都是 CSS3 可用的选择器,因此这是不可能的,这就是您的答案。
You have 2 options left without changing the content one is all ready described here:
您还有 2 个选项,无需更改此处描述的内容:
- javascript
- server-side parsing so everything gets wrapped with the span tag
- javascript
- 服务器端解析所以一切都被 span 标签包裹
回答by Kimmax
Use <span>
for this.
<span>
为此使用。
<div id="container"> This is a <span class="red">red</span> apple </div>
CSS:
CSS:
.red {
color: red;
}
Edit
It isn't possible without any additional Javascript or HTML. According to the CSS3 specificationthere is no such selector (There were thoughts about a :contains()
selector for CSS3). Also see thisand thisQuestion.
编辑
如果没有任何额外的 Javascript 或 HTML,这是不可能的。根据 CSS3规范,没有这样的选择器(有关于:contains()
CSS3 选择器的想法)。也看到这个和这个问题。
回答by codefreaK
- It cannot be done using only css selectors at present checkout documentation forCSS selectors
- 它不能对当前结账文档只使用CSS选择器来实现的CSS选择器
It can be easily Done with Jquery with a single line statements
使用单行语句可以轻松地使用 Jquery 完成
Highlighting and remove highlight on button click
使用鼠标选择特定单词时最简单的解决方案,该单词将在整个容器中突出显示
Jquery
查询
var text = $('div').text().replace(/Ipsum/g,"<span class='red'>Ipsum</span>");
$('div').html(text);
EDIT:
编辑:
$('#id1').click(
function(){
var text = $('div').text().replace(/Ipsum/g,"<span class='red'>Ipsum</span>");
$('div').html(text);
}
);
$('#id2').click(
function(){
$( "span.red" ).each(function() {
$( this ).contents().unwrap();
});
}
);
CSS
CSS
.red {
color: red;
}
HTML
HTML
<div>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>
EDIT:
编辑:
<input type="button" value="Click to highlight" id="id1" />
<input type="button" value="Click to remove highlight" id="id2" />
回答by graphicdivine
Use pseudo elementsto add the coloured word and some careful positioning to cover the initial black instance. It's dirty, but it works.
使用伪元素添加彩色单词和一些仔细定位以覆盖初始黑色实例。它很脏,但它有效。
#container
{
position: relative;
font-family: monospace;
margin: 0;
padding: 0;
font-size: 15px;
}
#container:after
{
content: "red";
color: red;
position: absolute;
left: 90px
}
EDIT: Also, a variation that works with proportional fonts (but doesn't render quite so cleanly, at least for me, in Chrome):
编辑:此外,还有一种适用于比例字体的变体(但在 Chrome 中渲染得不太干净,至少对我而言):
#container
{
position: relative;
margin: 0;
padding: 0;
}
#container:before
{
content: "This is a ";
position: absolute;
z-index: 2
}
#container:after
{
content: "This is a red";
color: red;
position: absolute;
left: 0;
top: 0;
z-index: 1
}
回答by Alex Faster
So I have the same task, and the solution is pretty simple, but tricky You need to add :after pseudo-element and then:
所以我有同样的任务,解决方案非常简单,但很棘手您需要添加 :after 伪元素,然后:
#container:after {
content: "";
position: absolute;
width: 200px;
height: 50px;
background-color: red;
top: 10px;
left: 100px;
z-index: -1;
}
Adjust top, left, height, width for your case.
根据您的情况调整顶部、左侧、高度、宽度。