细化jQuery的重点脚本

细化jQuery的重点脚本

本文介绍了细化jQuery的重点脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的jQuery脚本,当输入元素被关注时,它的宽度扩展到250px(使用 focusin()事件),当焦点丢失,使用 focusout()事件缩小到200px。但是我不确定我正在使用语法上最有效的代码来实现我想要达到的效果。这是我目前的代码:

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

然而对我来说,这似乎不必要的庞大。我试着用google搜索,但是我找不到关键词找到任何帮助我的结果。当然有一个更简单的方法来实现这样的效果,如切换?我将如何实现这一目标?

解决方案

我没有看到你做了什么错。如果你觉得自己太重复了,可以把一些逻辑放到 animateWidth 函数中:

<$ p $ {code> $(document).ready(function(){

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


$('input')。 function(){animateWidth($(this),'200px');});

});


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?

解决方案

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'); });

});

这篇关于细化jQuery的重点脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 13:03