unobtrusive “default” text in input WITHOUT jQuery

前端 未结 7 1776
攒了一身酷
攒了一身酷 2021-01-16 22:15

i\'m trying to write unobtrusive default/placeholder text in input (actually, relatively placed label over input, which hides on onFocus

7条回答
  •  攒了一身酷
    2021-01-16 22:49

    You can use jQuery and still be unobtrusive and use the ability of HTML5 Browsers, make your input like this:

    
    

    I user Modernizr to check the html5 capabilities of the browser and if the browser doesn't understand the placeholder attribute than I use this little javascript to emulate this function.

    if (!Modernizr.input.placeholder) {
      $('input').each(function(){
        var obj = $(this);
        var placeholder = obj.attr('placeholder');
        if (placeholder) {
          obj.val(placeholder);
          obj.focus(function(){
            var obj2 = $(this);
            if (obj2.val() == obj2.attr('placeholder')) obj2.val('');
          });
          obj.blur(function(){
            var obj2 = $(this);
            if (obj2.val() == '') obj2.val(obj2.attr('placeholder'));
          });
        }
      });
    }
    

    It is unobtrusive, because you don't need any javascript in your html code. the function above can easily changed if you want to use any other framework. I wouldn't use a solution without any Framework, because the frameworks do a great job in working around the incompatibilities between browsers.

提交回复
热议问题