2013-10-31 44 views

回答

6

placeholder是在HTML 5新

有一個在XHTML 1.x中沒有等價(這是HTML 4.x中的XML版本)

這是當然的,在XML可用HTML 5

做不到這一點的序列化,你就必須僞造它使用JavaScript(這可能是最好的做絕對定位在其下設置有一個透明的背景顏色,除非它有一個值<input>第二<label>元素或焦點)。

+0

謝謝你的回答。我一直假設有一個等效或替代方案直接使用xhtml。我會嘗試使用JavaScript。 – NYCity

1

我做了一個實驗來模擬使用xhtml + js + css作爲HTML5佔位符屬性發生的佔位符。

XHTML:

<input id="textbox-obj" type="text" class="search-txt" data-placeholder="Search" title="Search something here"> 

使用Javascript(jQuery的):

//Function to place the textbox cursor to the begining 
function moveCursorToStart(el) { 
    if (typeof el.selectionStart == "number") { 
     el.selectionStart = el.selectionEnd = 0; 
    } else if (typeof el.createTextRange != "undefined") { 
     el.focus(); 
     var range = el.createTextRange(); 
     range.collapse(true); 
     range.select(); 
    } 
} 

function initSearchTextPlaceholder(textBox) { 
    textBox.focus(function() { 
     if($(this).val() == $(this).attr('data-placeholder')) { 
     moveCursorToStart(this); 

     // To fix Chrome's bug 
     window.setTimeout(function() { 
      moveCursorToStart(this); 
     }, 1); 
     } 
    }).blur(function() { 
     if($(this).val() == $(this).attr('data-placeholder') || $(this).val() == '') { 
     $(this).addClass('placeholder').val($(this).attr('data-placeholder')); 
     } 
    }).on('keypress', function() { 
     if($(this).val() == $(this).attr('data-placeholder')) { 
     $(this).removeClass('placeholder').val(''); 
     } 
    } 
    ).blur(); 
} 

initSearchTextPlaceholder($("#textbox-obj")); 

CSS

.search-txt { 
    color: #333; 
} 
.search-txt.placeholder { 
    color: #8d8d8d; 
} 
相關問題