2012-12-09 29 views
11

我想添加一個jQuery的顏色選擇器後備,如果沒有顏色選擇器顯示。例如,chrome顯示一個顏色選擇器,但是到目前爲止,safari只是顯示一個文本框。有沒有辦法(無需用戶代理)檢測顏色選擇器是否可用?如何知道HTML5輸入類型的顏色是否可用作顏色選擇器?

編輯:Modernizr不好,因爲它只是說safari也支持它。 Safari支持輸入類型的顏色,因爲它不允許在輸入框中輸入任何東西,只有#hex顏色。但沒有顏色選擇器。我需要知道是否有顏色選擇器。

+4

您可以使用[Modernizr的(http://modernizr.com/)庫。 – undefined

+0

就是這麼說的。你擊敗了我。 –

+1

必須說,考慮到您的評論如下,這是一個很好的問題。 –

回答

2

在這裏你去。

/** 
 
* Determine if the current browser has support for HTML5 input type of color. 
 
* @author Matthew Toledo 
 
* @return {boolean} True if color input type suppored. False if not. 
 
*/ 
 
var test = function() { 
 
    var colorInput; 
 

 
    // NOTE: 
 
    // 
 
    // If the browser is capable of displaying a color picker, it will sanitize the color value first. So "!"" becomes #000000; 
 
    // 
 
    // Taken directly from modernizr: 
 
    // @see http://modernizr.com/docs/#features-html5 
 
    // 
 
    // These types can enable native datepickers, colorpickers, URL validation, and so on. 
 
    // If a browser doesn’t support a given type, it will be rendered as a text field. Modernizr 
 
    // cannot detect that date inputs create a datepicker, the color input create a colorpicker, 
 
    // and so on—it will detect that the input values are sanitized based on the spec. In the 
 
    // case of WebKit, we have received confirmation that sanitization will not be added without 
 
    // the UI widgets being in place. 
 
    colorInput = $('<input type="color" value="!" />')[0]; 
 
    return colorInput.type === 'color' && colorInput.value !== '!'; 
 
}; 
 

 
$(function(){ 
 
    if (test()) { 
 
    $('body').append('<p1>Your browser supports the color input</p>'); 
 
    } else { 
 
    $('body').append('<p>Your browser Doesn\'t Support the color input</p>'); 
 
    } 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>