给其他颜色留下h1的两个字母

时间:2015-11-11 01:31:02

标签: javascript jquery css

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

HTML

<h1>AwesoME</h1>

CSS

h1 {
color:#eee
}

h1:last-word {
color:#000
}

我只想更改h1的最后两个字母。是用javascript还是jQuery

2 个答案:

答案 0 :(得分:8)

这是一个jQuery解决方案:

&#13;
&#13;
$('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
});
&#13;
h1 {
  color:#eee
}

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

<小时/> 这是一个普通的JavaScript解决方案:

&#13;
&#13;
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
&#13;
h1 {
  color:#eee
}

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

答案 1 :(得分:2)

尝试使用css :after

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