所以我創建了這個函數從樣式屬性中提取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];
};
我真的不喜歡嵌套的分裂。有沒有更好的方法來做到這一點?
可能的重複[如何從CSS顏色中提取r,g,b,a值](http://stackoverflow.com/questions/3751877/how-to-extract-rgba-values-from-css-顏色) – Tom
這可能是有幫助的:https://stackoverflow.com/questions/3048838/jquery-css-color-value-returns-rgb – Ajwhiteway
這取決於,但如果你知道你只是得到RGB爲什麼不只是使用一個拆分,循環數組ParseInt的值和所有不是NaN的將是你的數字?它很髒,但會更簡單。 –