2016-01-21 24 views
0

所以我創建了這個函數從樣式屬性中提取RGB數組,但我內心的一切都在尖叫,告訴我有一個更好的方法。簡單的JavaScript函數從樣式屬性中提取RBG

我的風格屬性看起來是這樣的:

style="fill: rgb(0, 0, 0);" 

,所以我寫了一個函數,看起來像這樣:

var _extractRGBfromStyle = function (styles) { 

    // Create some variables 
    var length = styles.length - 1, 
     index = styles.indexOf(';'); 

    // If we only have one style applied to the element 
    if (length === index) { 

     // Get the first part 
     var rgb = styles.split('('); 

     // If we have more than one result 
     if (rgb.length > 1) { 

      // Get our last part 
      rgb = rgb[1].split(')'); 

      // If we have more than one result 
      if (rgb.length > 1) { 

       // Do one last split and return it 
       return rgb[0].split(','); 
      } 
     } 
    } 

    // Fallback 
    return [0, 0, 0]; 
}; 

我真的不喜歡嵌套的分裂。有沒有更好的方法來做到這一點?

+1

可能的重複[如何從CSS顏色中提取r,g,b,a值](http://stackoverflow.com/questions/3751877/how-to-extract-rgba-values-from-css-顏色) – Tom

+0

這可能是有幫助的:https://stackoverflow.com/questions/3048838/jquery-css-color-value-returns-rgb – Ajwhiteway

+0

這取決於,但如果你知道你只是得到RGB爲什麼不只是使用一個拆分,循環數組ParseInt的值和所有不是NaN的將是你的數字?它很髒,但會更簡單。 –

回答

0

我通過使用正則表達式回答了這個:

// Extract our hex from our style 
var _rgb2hex = function (style) { 

    // match our fill style 
    var rgb = style.match(/^fill:\s?rgb[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)\);/i); 

    // If our array exists and is a length of 4 
    if (rgb && rgb.length === 4) { 

     // Create our hex 
     var hex = ("0" + parseInt(rgb[1], 10).toString(16)).slice(-2) + ("0" + parseInt(rgb[2], 10).toString(16)).slice(-2) + ("0" + parseInt(rgb[3], 10).toString(16)).slice(-2); 

     // Return our hex 
     return hex; 
    } 

    // Fallback 
    return ''; 
}; 
0

據我知道這是唯一可能使用字符串分割,但你做的麪包車內聯正則表達式拆分,像這樣

yourstyleattribute.replace(/^RGBA(| \ S + |)$ /克, '')分裂( '')?;

它將所有的數字RBG值拆分成一個數組。

希望這會有所幫助。