细化jquery焦点脚本?

我有一个非常简单的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'); }); });