2012-05-31 32 views
0

我怎樣被格式化這樣的標籤:的標籤,消失的時候集中

<label for="email"> Email Address *</label> 
<input id="email" type="text" name="email" value="" size="18"> 

顯示輸入文本框內部,當輸入元件處於對焦或完全消失?

我找到的解決方案需要我修改html代碼,我不能這樣做,因爲它來自第三方小部件。我可以將標籤顯示在輸入字段的頂部,但我不知道如何讓它對輸入字段發生的反應做出反應。

+0

你不再需要這方面的幫助? – Melanie

回答

4

你想要的是一個佔位符。它是一個HTML5屬性,但不支持IE和舊瀏覽器。爲了填補,有一些圖書館在那裏。我用jquery.enablePlaceholder,它工作正常。

使用JQuery,您將能夠輕鬆地隱藏/刪除當前標籤並使用其內容填充佔位符屬性(如果需要,將由插件使用該屬性)。

$(document).ready(function() { 
    // Fetch the label and its text 
    var placeholderText = $("label[for='email']").text(); 

    // Remove the unnecessary label 
    $("label[for='email']").remove(); 

    // Set the placeholder attribute 
    // and enable the plugin for broswer not supporting it 
    $("#email").attr('placeholder', placeholderText).enablePlaceholder(); 
}); 
+0

Melanie,我用你的答案,謝謝!我可以通過這種方式改進以適應任何形式的任何數量的字段'$(「form label」)。each(function(){var field = $(this).attr('for'); $( '''').attr('placeholder',$(this).text()); $(this).remove();})' – Hernan

0

有什麼方法可以覆蓋輸入onFocus函數嗎?

如果爲陽性,有兩路:

  • 嘗試return false;
  • 集標籤display屬性inline該函數。 (不推薦 )
0

既然你不能改變的HTML結構,這裏是一個普通的JavaScript實現你的目標的手段:

function placeholding(el,greyed) { 
    if (!el) { 
     // if you don't specify a DOM node, it quits 
     return false; 
    } 
    else { 
     var input = el, 
      /* assumes the label element is the previous element sibling 
       (requires a fairly up-to-date/compliant browser */ 
      label = el.previousElementSibling, 
      placeholder = label.textContent, 
      /* specifies the color string, or uses the default, for the 
       color of the place-holder */ 
      greyed = greyed || '#999'; 

     label.style.display = 'none'; 
     input.value = placeholder; 
     input.style.color = greyed; 
     input.onfocus = function() { 
      /* if the current input-value is equal to the place-holder, 
       removes that value. */ 
      if (this.value == placeholder) { 
       this.setAttribute('data-oldvalue', this.value); 
       this.value = ''; 
      } 
      this.style.color = '#000'; 
     }; 
     input.onblur = function() { 
      // if no new value has been set, replaces the place-holder 
      if (this.value == '' || this.value.length === 0) { 
       this.value = this.getAttribute('data-oldvalue'); 
       this.style.color = greyed; 
      } 
     }; 
    } 
} 

placeholding(document.getElementById('email'));​​​​​ 

,它可以隱藏以前label元素,使用其文本input元素中的「佔位符」,隱藏該位置持有者以聚焦input,並且如果該值未更改,則再次顯示佔位符。

參考文獻:

0

如果你能使用jQuery:

$("#yourForm input[type='text']").each(function(){ 
    $(this).attr("placeholder", $(this).prev("label").text()); 
}