js设置字体颜色

JavaScript015

js设置字体颜色,第1张

js改变字体的颜色是用的“color”属性,xmlHttp.open("GET",URL,true)是设置ajax的请求地址和请求方式,不能去掉。

1、新建html文档,在body标签中添加p标签,标签内容是“演示文本”,这时字体的默认颜色是黑色的:

2、为了方便获取到这个p标签,给p标签添加上id,这里以“demo”为例:

3、添加script标签,在js标签中输入代码“document.getElementById('demo').style.color = '#f00'”,这样文本的字体颜色就变成了红色:

很简单的:

如果你是在学习JS、遇到了各种问题,那么你一定要来这个企鹅裙,前面前面是二九六,中间是五九一,最后面就是二九0,来这里可以得到专人解答,期待你的加入!!!

<div id="txt">我是要改变的文字</div>

<script>

//首先咱们找到要改变的文字

var txt = document.getElementById("txt")

//然后设置一个标记flag

var flag = true

//然后点击这个div或者按钮

txt.onclick = function(){

//改变里面文字颜色

if(flag){

this.style.color = "red"

flag = false

}else{

this.style.color = "#000"

flag = true

}

}

</script>

1、这个函数来自Rico,Longbill及Dnew.cn修改。

2、说明: 传入参数一个,为元素的id值或元素本身,返回为元素的真实背景色值(字符串)。背景值均为16进制的值(原代码是是IE里面返回的是16进制的值,而Mozilla则是rgb值,Dnew.cn将其修改为均返回16进制的值)。

3、代码如下:

<html>  

<head>  

<title>得到元素真实的背景颜色</title>  

<style>  

.classname  {background-color:#ff99dd}  

#div3  {background-color:#d8bfd8}  

div  {background-color:#87cefaborder:1px solid #333333margin:10pxpadding:4px}  

body  {background-color:#bed742}  

#div4  {background-color:transparent}  

</style>  

</head>  

<body>  

<span style="text-align:centerfont-size:20pxcolor:#ff7f50width:100%">得到元素真实的背景颜色 <font style="font-size:12px">By <a href=

<div id='div1'>div1 直接通过div标签定义背景色(#87cefa)</div>  

<div id='div2' class=classname>div2 通过class name定义背景色(#ff99dd)</div>  

<div id='div3'>div3 通过id定义背景色(#d8bfd8)</div>  

<div id='div4'>div4 这是一个透明的div,背景色应为上一个元素的颜色(#bed742)</div>  

<button onclick="go()">getBg()</button>  

<script>  

function getBg(element)  

{//author: Longbill (

)  

//dnew.cn修补  

  var rgbToHex=function(rgbarray,array){  

      if (rgbarray.length < 3) return false  

      if (rgbarray.length == 4 && rgbarray[3] == 0 && !array) return 'transparent'  

      var hex = []  

      for (var i = 0 i < 3 i++){  

        var bit = (rgbarray[i] - 0).toString(16)  

        hex.push((bit.length == 1) ? '0' + bit : bit)  

      }  

      return array ? hex : '#' + hex.join('')  

    }  

//---------------  

  if (typeof element == "string") element = document.getElementById(element)  

  if (!element) return  

  cssProperty = "backgroundColor"  

  mozillaEquivalentCSS = "background-color"  

  if (element.currentStyle)  

    var actualColor = element.currentStyle[cssProperty]  

  else  

  {  

    var cs = document.defaultView.getComputedStyle(element, null)  

    var actualColor = cs.getPropertyValue(mozillaEquivalentCSS).match(/\d{1,3}/g)  

//-----  

    actualColor = (actualColor) ? rgbToHex(actualColor) : "transparent"  

  }  

  if (actualColor == "transparent" && element.parentNode)  

    return arguments.callee(element.parentNode)  

  if (actualColor == null)  

    return "#ffffff"  

  else  

    return actualColor  

}  

function go()  

{  

  for(var i=1i<=4i++) eval("alert('div"+i+":'+getBg('div"+i+"'))")  

}  

</script>  

</body>  

</html>