程式設計師在網頁表單上通常會設計很多提示的功能,而在 Html5 提供了 placeholder attribute 這功能,目前 FireFox Safari Google Chrome 都沒有顯示上的問題,唯獨 IE8(含以下)都沒辦法顯示這功能,所以必須透過 javascript 來解決這部份問題了,網路上找到這篇解決方式,底下是原始碼
<script type="text/javascript">
// A no-dependancy quick and dirty method of adding basic
// placeholder functionality to Internet Explorer 5.5+
// Author: Jay Williams <myd3.com>
// License: MIT License
// Link: https://gist.github.com/1105055
function add_placeholder (id, placeholder)
{
var el = document.getElementById(id);
el.placeholder = placeholder;
el.onfocus = function ()
{
if(this.value == this.placeholder)
{
this.value = '';
el.style.cssText = '';
}
};
el.onblur = function ()
{
if(this.value.length == 0)
{
this.value = this.placeholder;
el.style.cssText = 'color:#A9A9A9;';
}
};
el.onblur();
}
// Add right before </body> or inside a DOMReady wrapper
add_placeholder('myInputField', 'IE Placeholder Text');
</script>
<![endif]-->
解決原理其實很簡單,那就先將 placeholder 寫入到 input value 裡面,在 focus event 當下比對 input value 是否等於 placeholder 的值,如果是就清空,反之透過 onblur event 來寫回原先的 placeholder 值,缺點就是如果當 input type = password 的時候會很麻煩。底下提供轉成 CoffeeScript 的程式碼:
el = document.getElementById(id)
el.placeholder = placeholder
el.onfocus = () ->
if(this.value == this.placeholder)
this.value = ''
el.style.cssText = ''
el.onblur = () ->
if(this.value.length == 0)
this.value = this.placeholder
el.style.cssText = 'color:#A9A9A9;'
el.onblur()
# Login Form
add_placeholder('myInputField', 'IE Placeholder Text')
如果有用 jQuery 的話,可以把第二個參數改寫成