简体   繁体   中英

jQuery onfocus and onblur event minification

As you can see I am trying to increase the height of the text field when the user types into it and when he clicks away (element loses focus) I am making it smaller.

Is there a simpler way to write the following code?

Simple HTML input field:

<input type="text" />

jQuery:

$(document).ready(function() {

    $('input').on('focus', function() {
        $(this).height('20px');
    });

    $('input').on('blur', function() {
        $(this).height('12px');
    });

});

This can be done more-efficiently with just CSS, but using jQuery, you could use event delegation.

$(document).on('focus blur', 'input', function(e) {
    $(this).height(e.type === 'focusin' ? '20px' : '12px');
})

For completeness, here's the CSS solution:

input {
    height: 12px;
}
input:focus {
    height: 20px;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM