javascript文字彩虹式顏色漸變效果程式碼例項

admin發表於2017-04-06

本章節分享一段程式碼例項它實現了文字的彩虹式顏色漸變效果。

在實際應用中也是有的,需要的朋友可以做一下參考。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script>
function createHexArray(n){
  this.length = n;
  for (var index = 1; index <= n; index++){
    this[index] = index - 1;
  }
  this[11] = "A";
  this[12] = "B";
  this[13] = "C";
  this[14] = "D";
  this[15] = "E";
  this[16] = "F";
  return this;
}
hx = new createHexArray(16);
function convertToHex(x){
  if (x < 17){
    x = 16;
  }  
  var high = x / 16;
  var s = high+"";
  s = s.substring(0, 2);
  high = parseInt(s, 10);
  var left = hx[high + 1];
  var low = x - high * 16;
  if (low < 1){
    low = 1;
  }
  s = low + "";
  s = s.substring(0, 2);
  low = parseInt(s, 10);
  var right = hx[low + 1];
  var string = left + "" + right;
  return string;
}
function makeRainbow(text,id){
  var ele=document.getElementById(id);
  var str="";
  text = text.substring(0, text.length);
  color_d1 = 255;
  mul = color_d1 / text.length;
  for(var index = 0; index < text.length; index++) {
    color_d1 = 255*Math.sin(index / (text.length / 3));
    color_h1 = convertToHex(color_d1);
    color_d2 = mul * index;
    color_h2 = convertToHex(color_d2);
    k = text.length;
    j = k - index;
    if (j < 0){
      j = 0;
    }  
    color_d3 = mul * j;
    color_h3 = convertToHex(color_d3);
    str=str+"<font color=\"#"
    + color_h3 + color_h1 + color_h2
    + "\">" + text.substring(index, index + 1)
    + "</font>";
  }
  ele.innerHTML=str;
}
window.onload=function(){
  makeRainbow("螞蟻部落的url地址是softwhy.com","show");
}
</script>
</head>
<body>
<div id="show"></div>
</body>
</html>

相關文章