2012-07-24 97 views
0

我在我的應用程序中使用了輸入框的佔位符,對於不支持佔位符的瀏覽器使用jQuery解決方法。但是,在大多數瀏覽器中,即使輸入爲空時,佔位符也會消失。一種解決方法是在輸入字段上使用透明bg,並將輸入字段後面的文本放在輸入字段後面,並在輸入內容後將bg更改爲不透明。問題是我的應用程序現在有超過3000個輸入字段。這是可能通過運行時通過jquery插件做到這一點?或者我願意提供更好的建議。請幫忙。HTML永久佔位解決方法

回答

0

這是我寫的和正在使用:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script> 
<style> 
body{ 
    background-color:#DDD; 
} 

span.placeholder 
{ 
    background-color:#FFF; 
    color:#777; 
    border-radius: 4px 4px 4px 4px; 
    margin: 5px 0; 
    padding: 9px 0 8px 13px; 
    width: 297px; 

} 
input 
{ 
    border: 1px solid #707A68; 
    border-radius: 4px 4px 4px 4px; 
    margin: 5px 0; 
    padding: 10px; 
    width: 310px; 
    background:transparent; 
} 

</style> 

<body> 
<div> 
    <input type="text" placeholder="hello" name="hh"/> 
</div> 
</body> 

<script> 
$('input').each(function(){ 

    var txt = $(this).attr('placeholder'); 
    var name = $(this).attr('name'); 
    var node = $("<span class='placeholder'>"+txt+"</span>").appendTo($(this).parent()); 
    $(this).before(node); 
    node.css('position','absolute'); 
    node.css('z-index','-1'); 
    node.css('display','block'); 
    $(this).attr('placeholder',''); 
}); 
$('input').bind('keyup',function(){ 
    if($(this).val()=="") 
     $(this).css('background','transparent'); 
    else 
     $(this).css('background','#FFF'); 
}); 
</script> 
1

你在同一頁面上有3000個輸入字段嗎?在這種情況下,您需要以某種方式重新設計您的應用程序。

如果您在多個頁面上有不同的輸入,並希望插件能夠在需要時自動產生佔位符,那麼可以使用一些很好的插件。以下是polyfills的綜合列表 - 只需查找「Web Forms:input placeholder」標題即可。 https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills

其中大多數不需要針對每個實例專門調用,因此您應該避免修改3000行代碼。 :)

+0

不是在同一個頁面!這是一個非常大的應用程序 – SNAG 2012-07-24 07:56:18

+0

你的意思是給一個鏈接? – SNAG 2012-07-24 09:21:46

+0

呃 - 對不起。編輯我的答案。 – 2012-07-24 15:05:47

0

我會使用值attr而不是邏輯將如下所示。

var input = document.createElement('input'); 
if(! ('placeholder' in input)) 
{ 
    $("input[placeholder]").focus(/* clear value if it is equals placeholder */); 
    $("input[placeholder]").blur(/* assign placeholder if it is "" */); 
    $("input[placeholder]").each(/* assign placeholder if value equals "" */) 
} 

您還可以更改焦點和模糊輸入的樣式(或類),以便它看起來更像佔位符。