简体   繁体   English

使用CSS或JS定位单词中的字母以更改颜色?

[英]Targeting letters within a word to change colour using CSS or JS?

I'm trying to figure out if there's a quicker way to write something like this: 我试图找出是否有一种更快的方式来写这样的事情:

<span class="brandname"><span style="color: #0399f0">Company</span>Name</span> <span class="tagline">TagLine</span> 

What should happen is CompanyName gets wrapped in the class brandname which is a specific font, weight, and text-decoration, and then first half of the name (Company) should be in blue while while the rest of it is default (black). 应该发生的是,CompanyName被包装在类brandname ,该brandname是一种特定的字体,粗细和文本修饰,然后名称的前半部分(公司)应为蓝色,而其余部分为默认值(黑色)。 And then Tagline is wrapped in a class called tagline which displays a different font etc. 然后,标语被包装在称为tagline的类中,该类显示不同的字体等。

Does anyone know if I can just use the class brandname to target the first half of CompanyName. 有谁知道我是否可以仅使用类brandname来定位CompanyName的前半部分。 Looking for a way to save keystrokes for the future. 寻找一种方法来保存将来的击键。

I feel like the way I'm doing it now would affect SEO. 我觉得我现在的方式会影响SEO。 Majority of my googling has resulted in links from 2012-2014...my guess is nth-letter still doesn't exist but was worth asking for alternative. 我的大部分Google搜索都导致了2012-2014年的链接...我的猜测是第n个字母仍然不存在,但值得寻求替代方法。

Thanks for your help! 谢谢你的帮助!

I ran into the same before. 我之前碰到过一样。 Unfortunately I couldn't find CSS only solution. 不幸的是,我找不到仅CSS解决方案。

Then I stumbled upon this pen . 然后我偶然发现了这支笔 This uses jQuery to style the n-th selector. 这使用jQuery设置第n个选择器的样式。

 /* # nth-Everthing made with js. # ##Implemented nth- ## :nth-letter :nth-word ## Implemented last-## :last-word :last-letter ## Implemented first- ## :first-word (faster than :nth-word(1)) ## Things that work ## Add a hover effet to each odd letter .className:nth-letter(odd):hover{} Add a hover effect to :before/:after .className:nth-letter(odd):hover:after{} ## Things that don't and will not work ## .className:before:nth-letter Read more: https://css-tricks.com/a-call-for-nth-everything/ */ (function($) { /*jshint loopfunc:true, onevar:true*/ /*global jQuery:true, browser:true */ $.fn.nthEverything = function() { var styleSuffix = "-nthEvery", cssPattern = /\\s*(.*?)\\s*\\{(.*?)\\}/g, cssComments = /\\s*(?!<\\")\\/\\*[^\\*]+\\*\\/(?!\\")\\s*/gm, partsPattern = /([^:]+)/g, nthPattern = /(\\w*)-(\\w*)(\\((even|odd|[\\+-n\\d]{1,6})\\))?/, wordSpacePattern = /(\\s*[^ ]+\\s*)/g, wordSimplePattern = /\\s+/, count, // To store the style per Selector parsedStyleMap = {}, // CSS for the classes genCSS = '', runPeriods = function(period, className, a, length, offset){ var inBy = 0, sAt = +period, matches, n, zB, zE, bF, eF, oldN = -1; if (period === 'odd' || period === 'even'){ sAt = (period === 'odd') ? 1 : 2; inBy = 2; }else if (/^\\d+$/.test(period)){ sAt = period - offset; inBy = 0; }else{ zB = /^(\\+|-)?\\d+/.exec(period); zE = /(\\+|-)?\\d+$/.exec(period); sAt = (zE)?+(zE[0]):1; inBy = (zB)?+(zB[0]):1; bF = (zB)?zB.length-1:0; eF = (zE)?zE.length:0; if ((period.substr(bF, period.length-eF-bF).charAt(0)) === '-'){ inBy*=-1; } } // Start index at 0; sAt--; for (n=sAt;n<length;n+=inBy){ if (n < 0 || n === oldN) break; if (a[n] === undefined){ a[n] = className; }else{ a[n] += " "+className; } oldN = n; } }, createSpan = function(className, content){ return '<span class="'+className+'">'+content+'</span>'; }, processPeriod = function(classNames, textArray){ var newText = '', n, className; for (n=0;n<classNames.length;n++){ className = classNames[n]; if (className === undefined){ newText += textArray[n]; }else{ newText += createSpan(className, textArray[n]); } } return newText; }, getClassNames = function(parsedStyle, length, pFunc){ var classNames = new Array(length), i; for (i=0;i<parsedStyle.period.length;i++){ runPeriods (pFunc(parsedStyle.period[i], length), parsedStyle.className[i], classNames, length); } return classNames; }, prepareTxt = { word : function(text){return text.match(wordSpacePattern);}, letter: function(text){return text.split('');} }, pseudoFunc = { first : { word : function(period){ if (period === 'firstword') period = '1'; return period; } }, last : { word : function(period, allText, length){ if (period === 'lastword') period = ''+allText.match(wordSpacePattern).length; return period; } }, nth : { letter : function (period){ return period; }, word : function(period){ return period; } } }, loopRecursive = function (contents, allText, parsedStyle){ var func = parsedStyle.func, text, length, classNames, className, cat, period; contents.each(function(){ if (this.nodeType === 1){ loopRecursive($(this).contents(), allText, parsedStyle); }else if(this.nodeType === 3){ text = prepareTxt[func](this.nodeValue); length = text.length; classNames = new Array(length); for (var i=0;i<parsedStyle.period.length;i++){ className = parsedStyle.className[i]; cat = parsedStyle.cat[i]; period = parsedStyle.period[i]; runPeriods (pseudoFunc[cat][func](period, allText, length), className, classNames, length, count); } $(this).replaceWith( processPeriod(classNames, text) ); count += length; } }); return count; }, parse = function(css) { var matches, nthMatch, nthFound = false, i, thisPeriod, selectors, style, selector, parts, nth, pseudo, cat, func, period, normSelector, ident, className; css = css.replace(cssComments, '').replace(/\\n|\\r/g, ''); while ((matches = cssPattern.exec(css)) !== null){ selectors = matches[1].split(','); style = matches[2]; for (i=0;i<selectors.length;i++){ selector = selectors[i]; parts = selector.match(partsPattern); selector = parts.shift(); nth = parts.shift(); pseudo = (parts.length !== 0)?':'+parts.join(':'):''; if ((nthMatch = nthPattern.exec(nth)) !== null){ nthFound = true; cat = nthMatch[1]; func = nthMatch[2]; period = (nthMatch[4]!==undefined)?nthMatch[4]:cat+func; normSelector = selector.replace('#','id').replace('.', 'class'); ident = normSelector + func; className = normSelector + cat + func + period + styleSuffix; if ((thisPeriod = parsedStyleMap[ident]) !== undefined){ thisPeriod.className.push(className); thisPeriod.period.push(period); thisPeriod.style.push(style); thisPeriod.pseudo.push(pseudo); thisPeriod.cat.push(cat); }else{ parsedStyleMap[ident] = {element : selector, func : func, className : [className], cat : [cat], period : [period], style :[style], pseudo : [pseudo]}; } }else if (nthFound === true){ genCSS += selector+"{"+style+"}"; // Fix chained selectors. } } } }, applyStyles = function(){ var id, parsedStyle, func, b; for (id in parsedStyleMap){ parsedStyle = parsedStyleMap[id]; func = parsedStyle.func; $(parsedStyle.element).each(function(){ var $this = $(this); count = 0; // Set to 0. We use a recursive Loop here loopRecursive($this.contents(), $this.text(), parsedStyle); }); for (b=0;b<parsedStyle.className.length;b++){ genCSS += "."+parsedStyle.className[b]+parsedStyle.pseudo[b]+"{"+parsedStyle.style[b]+"}"; } } $('<style>' + genCSS + '</style>').appendTo('head'); }; // Build CSS Rules $('link[rel=stylesheet],style').each(function() { if ($(this).is('link')) $.get(this.href).success(function(css) { parse(css); }); else parse($(this).text()); }); // Apply Styles. applyStyles(); }; })(jQuery); $.fn.nthEverything(); 
 .brandname2:nth-word(1){ color: red; font-size: 25px; } .brandname2:nth-word(2) { color: green; font-size: 20px; } .brandname2 { color: purple; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> </ br> <div class="brandname2">Company name Tagline</div> 

You could do something like this CSS only, but in this case you have to add the content you want in another color to the css part: 只能执行类似以下CSS的操作,但是在这种情况下,您必须将想要的内容以另一种颜色添加到CSS部分:

HTML: HTML:

<span class="brandname">Name</span> <span class="tagline">TagLine</span>

CSS: CSS:

.brandname::before {
  content: "Company ";
  color: #0399f0;
}

I myself would still prefer the solution with the 2 span elements. 我自己还是会比较喜欢使用2个span元素的解决方案。

Working fiddle: https://jsfiddle.net/xeyqr4w9/ 工作提琴: https : //jsfiddle.net/xeyqr4w9/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM