DIV CSS 佈局教程網

用 JavaScript 在 RGB 與十六進位色碼之間自由轉換
編輯:關於JavaScript     

設計師給的是 #defdcd,CSS 裡寫的是 rgb(...),canvas 或某些計算又只吃其中一種格式。與其每次手動換算,不如封裝成一個小工具。

使用方式

Color(12, 34, 56);
Color("#fff");
Color("#defdcd");

三種寫法都吃:直接給 RGB 三個數字,或給十六進位色碼(#fff 這種三位數的簡寫也支援,會自動展開成 #ffffff)。

實作程式碼

// 顏色轉換
var Color = function () {
  if (!(this instanceof Color)) {
    var color = new Color();
    color._init.apply(color, arguments);
    return color;
  }
  if (arguments.length) {
    this._init.apply(this, arguments);
  }
};

// 動態產生 get / set 方法
var methods = ["red", "green", "blue", "colorValue"];

var defineSetGetMethod = function (fn, methods) {
  var fnPrototype = fn.prototype;
  for (var i = 0; i < methods.length; i++) {
    var methodName = methods[i].charAt(0).toLocaleUpperCase() + methods[i].substring(1);
    fnPrototype['set' + methodName] = new Function("value", "this." + methods[i] + " = value;");
    fnPrototype['get' + methodName] = new Function("return this." + methods[i] + ";");
  }
  fnPrototype['toString'] = new Function(
    'return "rgb(" + this.red + "," + this.green + "," + this.blue + ")";'
  );
};

defineSetGetMethod(Color, methods);

// 擴充實例方法
var extend = function (fn, option) {
  var fnPrototype = fn.prototype;
  for (var i in option) {
    fnPrototype[i] = option[i];
  }
};

extend(Color, {
  _init: function () {
    if (arguments.length == 3) {
      this.red = arguments[0];
      this.green = arguments[1];
      this.blue = arguments[2];
      this.getColorValue();
    } else {
      var colorValue = arguments[0].replace(/^\#{1}/, "");
      if (colorValue.length == 3) {
        colorValue = colorValue.replace(/(.)/g, '$1$1');
      }
      this.red = parseInt('0x' + colorValue.substring(0, 2), 16);
      this.green = parseInt('0x' + colorValue.substring(2, 4), 16);
      this.blue = parseInt('0x' + colorValue.substring(4), 16);
      this.colorValue = "#" + colorValue;
    }
  },

  getColorValue: function () {
    if (this.colorValue) {
      return this.colorValue;
    }
    var hR = this.red.toString(16);
    var hG = this.green.toString(16);
    var hB = this.blue.toString(16);
    return this.colorValue = "#" +
      (this.red < 16 ? ("0" + hR) : hR) +
      (this.green < 16 ? ("0" + hG) : hG) +
      (this.blue < 16 ? ("0" + hB) : hB);
  }
});

幾個值得留意的設計細節

不用 new 也能呼叫。開頭那段 if (!(this instanceof Color)) 的檢查,讓 Color(12,34,56) 與 new Color(12,34,56) 都能正常運作,這在打造類似 jQuery 那種介面時很常見。

三位數色碼的展開技巧。colorValue.replace(/(.)/g, '$1$1') 用一個巧妙的替換,把 fff 變成 ffffff,比寫 if 判斷再逐字複製來得乾淨。

補零是必要的。轉回十六進位時,(0).toString(16) 只會得到 "0" 一個字元,若 (0, 0, 0) 不補零就會產生 #000 這種殘缺色碼。程式碼裡用 < 16 判斷來補上前導 0,正是處理這件事。

toString 讓物件自帶描述。掛上 toString() 之後,直接 alert 或字串拼接就會得到 rgb(12,34,56),除錯時方便不少。

補充一句:這段程式碼大量使用 new Function() 動態產生函式,寫法很聰明,但會繞過引擎的靜態分析、效能也略遜。現代做法會直接改用 Object.defineProperty 定義 getter/setter,語意更清楚,也不必跑字串編譯。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved