Thinning down a jquery focus script?

北城以北 提交于 2020-01-04 06:08:30

问题


I have a really simple jQuery script which when an input element is focused on, it expands its width to 250px (using the focusin() event), and when the focus is lost, it shrinks back to 200px using the focusout() event. But I'm not sure I'm using the most syntactically efficient code for what I'm trying to achieve. Here is my current code:

$(document).ready(function() {
    $('input').focus(function() {
        $(this).animate({
            width: "250px"
        }, 500);
    });
    $('input').focusout(function() {
        $(this).animate({
            width: "200px"
        }, 500);
    });
});

To me however, this seems unnecessarily bulky. I've tried googling around, but I can't get the keywords right to find any results which help me. Surely there is a much simpler method to achieve such an effect, like a toggle? How would I achieve this?


回答1:


I see nothing wrong with what you've done. If you feel you're repeating yourself too much, you might pull out some logic into a animateWidth function:

$(document).ready(function() {

    function animateWidth(element, width) {
        element.animate({ width: width }, 500);
    }

    $('input').focus(function () { animateWidth($(this), '250px'); })
              .focusout(function () { animateWidth($(this), '200px'); });

});


来源:https://stackoverflow.com/questions/8692240/thinning-down-a-jquery-focus-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!