2013-02-26 57 views

回答

1

好了,没有什么语言内置的。将十六进制转换为十进制就像CLng("&H" & hexValue)一样简单,但是从快速查看PHP手册中看到,hexdec()方法忽略任何无效字符,而VBScript CLng()只会崩溃。

因此,这里是一个工作的功能,据我可以告诉做同样的事情:

Function GetContrast50(hexColor) 
    Const strValidChars = "1234567890abcdef" 
    Dim maxValue, decValue, sanitizedColor 
    Dim x, curChar 
    sanitizedColor = "" 
    For x=1 To Len(hexColor) 
     curChar = LCase(Mid(hexColor, x, 1)) 
     If InStr(strValidChars, curChar)>0 Then 
      sanitizedColor = sanitizedColor & curChar 
     End If 
    Next 
    If Len(sanitizedColor)=0 Then 
     GetContrast50 = "invalid color string" 
     Exit Function 
    End If 
    maxValue = CLng("&H" & "ffffff") 
    decValue = CLng("&H" & sanitizedColor) 
    If decValue > (maxValue/2) Then 
     GetContrast50 = "black" 
    Else 
     GetContrast50 = "white" 
    End If 
End Function 

这是很容易扩展的验证检查给定的字符串是在有效范围内。

+1

感谢您的代码,它似乎做我在找什么。 – jbwharris 2013-02-27 16:11:43

+0

我注意到它正在进行的计算有一个问题。使用像#FFE6E6(淡粉红色)这样的值,我最终返回白色,这太轻而无法打开白色文本。我不确定在计算中是否存在问题。 – jbwharris 2013-02-27 19:34:34

+0

@jamEs哦,我的,对不起!由于在我的代码中“#FFE6E6”中的n00bish错误实际上被视为“66”,因为大写字母被认为是非法字符。现在修复它,看我的编辑。 – 2013-02-27 20:57:04