2015-10-01 60 views
3

我當前正在研究HTML表單,並且當我發現(偶然發現)輸入類型'color'實際上在chrome中創建了顏色選擇器(以及firefox http://caniuse.com/#feat=input-color)時需要創建顏色選擇器。 。HTML顏色選擇器輸入

enter image description here

<input type="color" value="#333" />

是否有使用顏色輸入型與優雅故障轉移到其他選擇的任何例子嗎?

此外,它將是很好的顯示十六進制值生成。在鉻中,它只顯示一個帶有選定顏色背景的按鈕框。

有沒有一種方法來設置HTML顏色輸入以顯示所選顏色的十六進制值?

+0

是否有任何HTML屬性故障轉移到別的嗎?答案是否定的。 – Rob

回答

1

是否有任何使用顏色輸入類型優雅地故障轉移到其他選擇器的例子?

如果顏色輸入不可用,您可以找到方法優雅地回退到另一個顏色選擇器。例如,https://github.com/bgrins/spectrum。 (嘗試搜索其他選項的「輸入顏色填充」)。

有沒有一種方法來設置HTML顏色輸入以顯示所選顏色的十六進制值?

對於我的Chrome(45.0.2454.93),它在選擇時顯示顏色選擇器中的十六進制值。如果您想在選擇後顯示它,則輸入值將顯示爲十六進制。

document.querySelector('input[type=color]').value 

如果你想顯示給用戶,你可以使用該值時onchange觸發input元素填充另一個元素。

+0

我試圖避免在另一個元素中顯示十六進制值。如果瀏覽器不支持顏色輸入類型,您可能會有重複的信息。如果有一個乾淨的CSS解決方案,這將是很好的。 –

+0

如果你確實需要一個元素,你可以在JS中使用'content(#xxxxxx)'設置CSS':before'或':after'。 – arcyqwerty

+0

我不知道是否有一種方法可以通過javascript調用本地瀏覽器的顏色選擇器並捕獲結果? –

1

這裏是我最終使用:

$("input.color").each(function() { 
 
    var that = this; 
 
    $(this).parent().prepend($("<i class='fa fa-paint-brush color-icon'></i>").click(function() { 
 
    that.type = (that.type == "color") ? "text" : "color"; 
 
    })); 
 
}).change(function() { 
 
    $(this).attr("data-value", this.value); 
 
    this.type = "text"; 
 
});
label { 
 
    font-family: sans-serif; 
 
    width: 300px; 
 
    display: block; 
 
    position: relative; 
 
} 
 
input { 
 
    padding: 5px 15px; 
 
    font-size: 16px; 
 
    width: 100%; 
 
    box-sizing: border-box; 
 
} 
 
input[type=color] { 
 
    padding: 0; 
 
    border: 0; 
 
    height: 40px; 
 
} 
 
input[type=color]:after { 
 
    content: attr(data-value); 
 
    position: absolute; 
 
    bottom: 10px; 
 
    text-align: center; 
 
    color: #fffff5; 
 
    display: block; 
 
    width: 100%; 
 
} 
 
.color-icon { 
 
    position: absolute; 
 
    bottom: 10px; 
 
    right: 10px; 
 
    color: #666; 
 
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.css" rel="stylesheet" /> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<label> 
 
    Color: 
 
    <br /> 
 
    <input class="color" placeholder="#XXXXXX" data-value="#xxxxxx" /> 
 
</label>