简体   繁体   English

更改标签的颜色

[英]Changing the colour of a <b> tag

I am trying to change the color of this text to green using JavaScript, but I get a warning about it being a bad object and the script crashes. 我正在尝试使用JavaScript将文本的颜色更改为绿色,但收到警告,提示它是错误的对象,脚本崩溃。

<html>
<head>

<style>

b   {

    color: #0000FF;
}

</style>

<script>

function resizea()  {

  var a = document.getElementsByTagName("b");
  a.style.color = "#00FF00";
}

</script>

</head>
<body onload="resizea()">

<b>I am blue</b>

</body>
</html>

since getElementsByTagName("b") return a collection of elements, you need to get the first one: 由于getElementsByTagName("b")返回元素的集合,因此您需要获取第一个元素:

var a = document.getElementsByTagName("b")[0];

Note the index between brackets [0] 注意括号之间的索引[0]

A little more verbose way, but hopefully more clear. 更详细的方法,但希望更清晰。 Go thou all the b elements and change their color: 遍历所有b元素并更改其颜色:

  var boldTags = document.getElementsByTagName ("b");

  console.log("There are " + boldTags.length + " bold elements");
  for (var i = 0; i < boldTags.length; i++) {
      var boldTag = boldTags[i]; 
      boldTag.style.color = "#00FF00";
      console.log("Element indexed  " + (i + 1) + " has color of \n" + boldTag.style.color);
   }

如果页面中有多个<b>标记,则可以使用以下代码更改所有粗体文本的颜色。

$("b").attr("style","color:#00FF00;")

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

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