【问题标题】:Give other color to last two letters of word of h1给 h1 单词的最后两个字母赋予其他颜色
【发布时间】:2015-11-11 01:31:01
【问题描述】:

我有一个 h1 标签,代码看起来像这样

HTML

<h1>AwesoME</h1>

CSS

h1 {
color:#eee
}

h1:last-word {
color:#000
}

我只想更改 h1 的最后两个字母。是否可以使用 javascript 或 jQuery

【问题讨论】:

标签: javascript jquery css


【解决方案1】:

这是一个 jQuery 解决方案:

$('h1').html(function() {
  var txt= $(this).text();
  return txt.substr(0, txt.length-2)          //all but the last two characters
         + '<span>'+txt.slice(-2)+'</span>';  //put last two characters in a span
});
h1 {
  color:#eee
}

h1 span {     /* different color for span */
  color:#000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>AwesoME</h1>


这是一个普通的 JavaScript 解决方案:

var h1= document.querySelector('h1'),
    txt= h1.textContent;

h1.innerHTML= txt.substr(0, txt.length-2)          //all but the last two characters
              + '<span>'+txt.slice(-2)+'</span>';  //put last two characters in a span
h1 {
  color:#eee
}

h1 span {     /* different color for span */
  color:#000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>AwesoME</h1>

【讨论】:

  • 只是为了迂腐,OP没有指定jQuery标签
  • 是的,但他写道,“使用 javascript 或 jQuery 是否可行。”在原生 JavaScript 中也很容易做到。
  • 添加了原生 JavaScript 解决方案。
  • 是的。您可以将h1:hover 用于整个h1,或者h1 span:hover 仅用于span
  • 当然:document.querySelector('h1').id= 'myID'
【解决方案2】:

尝试使用css :after

h1 {
  color: #eee;
}
h1:after {
  content: "ME";
  position: relative;
  color: #000;
  left:-50px;
}
&lt;h1&gt;AwesoME&lt;/h1&gt;

【讨论】:

    猜你喜欢
    • 2012-03-05
    • 2011-06-24
    • 1970-01-01
    • 2021-09-15
    • 2011-10-02
    • 2018-11-24
    • 2016-02-08
    • 1970-01-01
    相关资源
    最近更新 更多