jQuery/javascript - Input fields (user,pass) just like twitter's login?

后端 未结 6 694
萌比男神i
萌比男神i 2021-01-21 13:14

How can I achieve the same effect like twitter\'s log-in form (the top on the right) - when you click on the username/pass the value \"username\" stays there until you enter tex

相关标签:
6条回答
  • 2021-01-21 13:42

    I would just use the HTML5 placeholder attribute.

    Twitter actually uses spans and styles them in place of the input text box placeholder and would use javascript to remove them on the focus of the input box.

    The easiest way of doing this is use HTML5 placeholder with cross browser fallback of modernizr which is this.

    <script>
    $(document).ready(function(){
    
    if(!Modernizr.input.placeholder){
    
        $('[placeholder]').focus(function() {
          var input = $(this);
          if (input.val() == input.attr('placeholder')) {
            input.val('');
            input.removeClass('placeholder');
          }
        }).blur(function() {
          var input = $(this);
          if (input.val() == '' || input.val() == input.attr('placeholder')) {
            input.addClass('placeholder');
            input.val(input.attr('placeholder'));
          }
        }).blur();
        $('[placeholder]').parents('form').submit(function() {
          $(this).find('[placeholder]').each(function() {
            var input = $(this);
            if (input.val() == input.attr('placeholder')) {
              input.val('');
            }
          })
        });
    
    }
    
    </script>
    

    To change the style of the placeholder you can do something like this.

    input[placeholder]:focus {
      // change style of placeholder on focus
    }
    
    0 讨论(0)
  • 2021-01-21 13:50

    You could use the answer for Delete default value of an input text on click or if you fancy some HTML5 forms there is now native support for this functionality; it is called the placeholder-attribute.

    Twitter actually uses a '' inside a <div> wrapper and JavaScript to achieve this affect.

    <div class="holding username">
        <input type="text" id="username" value="" name="session[username_or_email]" title="Username or email" autocomplete="on">
        <span class="holder">Username</span>
    </div>
    
    0 讨论(0)
  • 2021-01-21 13:50

    here is a novel and easy idea for simple log in forms, until the html5 "placeholder" is better supported: We all know you cant change password fields to text, so showing default text is tricky, or you need another hidden input box.

    Why not use a background image?? On focus set to none, and then on blur, if the value is empty, put it back. Very easy and well supported. The only drawback is that your default text is not text, but an image. I can't think of anything that this would effect negatively, as far as usability.

    0 讨论(0)
  • 2021-01-21 13:57

    I've coded a plugin to do this, couldn't find any that use the twitter-like div default value.

    See working fiddle: http://jsfiddle.net/garreh/nCCPQ/2/


    jQuery: $.defaultText plugin

    // Basic Usage:
    $('input').defaultText({ text: 'Username' });
    
    // Provide a class to use:
    $('input').defaultText({ text: 'Email address', css: 'enter_email' });
    
    
    $.fn.defaultText = function(options) {
        var defaults = {
            css: 'dimmed'
        };
       
        var options = $.extend({}, defaults, options);
        
        if (!('text' in options)) return this;
        
        var input = this[0],
            $input = this,
            offset = $input.offset();
           
        function hide() {
          $div.hide();
          $input.add($div).removeClass(options.css);
        };
        
        function show() {
           $div.show();
           $input.add($div).addClass(options.css);
        }
            
        function focus() {
            if (input.value.length) hide();
            else show();
        };
        
        // Create div to put placeholder text in
        var $div = $('<div>' + options.text + '</div>')
            // Position it to the same place as the input box:
            .css({ position: 'absolute',
                   top: offset.top,
                   left: offset.left + 4,
                   cursor: 'text'
                })
            .click(function() {
                $input.focus();
                focus();
            })
            .addClass(options.css + ' unselectable')
            .appendTo('body');
        
        // Also add the class to the input box:
        $input
            .addClass(options.css)
            .keyup(focus).blur(function() {
                if (!input.value.length) show();
            });
        
        return this;
    };
    

    465 bytes minified, 323 gzipped:

    $.fn.defaultText=function(a){function d(){c.show();b.add(c).addClass(a.css)}
    function e(){f.value.length?(c.hide(),b.add(c).removeClass(a.css)):d()}
    a=$.extend({},{css:"dimmed"},a);if(!("text"in a))return this;var f=this[0],
    b=this,g=b.offset(),c=$("<div>"+a.text+"</div>").css({position:"absolute",
    top:g.top,left:g.left+4,cursor:"text"}).click(function(){b.focus();e()})
    .addClass(a.css+" unselectable").appendTo("body");b.addClass(a.css).keyup(e)
    .blur(function(){f.value.length||d()});return this};
    
    0 讨论(0)
  • 2021-01-21 14:04

    Thanks Garry. To eliminate the time lag in between user's typing and fading of default text, you can replace the focus function given above with following function

    function focus() {
            if ($(this).val()) hide();
            else show();
        };
    

    It eliminates the time lag.........

    0 讨论(0)
  • 2021-01-21 14:05

    HTML:

    <input type="text" title="User Name" value="User Name" class="username">
    

    jQuery:

    $('input.username')
    .focus(function(){
      var $this = $(this);
      if ($this.val() == $this.attr('title')) {
        $this.val('').removeClass('dimmed');
      }
    })
    .blur(function(){
      var $this = $(this);
      if ($this.val().length == 0){
        $this.val($this.attr('title')).addClass('dimmed');
      }
    });
    

    CSS:

    input.username {
      color: #000;
    }
    input.username.dimmed {
      color: #888;
    }
    
    0 讨论(0)
提交回复
热议问题