精简jquery焦点脚本

Thinning down a jquery focus script?

本文关键字:脚本 焦点 jquery 精简      更新时间:2023-09-26

我有一个非常简单的jQuery脚本,当输入元素聚焦时,它将其宽度扩展到250px(使用focusin()事件),当焦点丢失时,它将使用focusout()事件收缩回200px。但是我不确定我是否使用了语法上最有效的代码来实现我想要实现的目标。下面是我当前的代码:

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

然而,对我来说,这似乎不必要的笨重。我试过用谷歌搜索,但我找不到合适的关键词来找到任何对我有帮助的结果。要达到这种效果,肯定有更简单的方法,比如切换吧?我该如何做到这一点?

我看不出你所做的有什么不妥。如果你觉得你重复了太多,你可以把一些逻辑拉进animateWidth函数:

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