【问题标题】:how to use jquery to change background color of textbox for 3 seconds?如何使用 jquery 更改文本框的背景颜色 3 秒?
【发布时间】:2013-03-28 05:20:06
【问题描述】:

我正在做一个文本框,如果不符合要求,则背景将变为黄色,但我只希望背景保持黄色 3 秒....我该怎么做?

这是我目前拥有的,但黄色背景仍然存在......

$("#form").on("submit",function(){


user = $("#username").val().length;
userErrorBg = $('#username').css('background','yellow');


if(user < 3 || user > 6)
{

    setInterval("userErrorBg",0);

}

})

我正在考虑在某处放置一个 clearInterval,但我需要一个时间计数,对吗?

【问题讨论】:

    标签: jquery forms time submit


    【解决方案1】:

    如果您认为setTimeout(function(){},time) 在特定时间段内只工作一次,则最好使用setInterval(function(){}, time),而不是在给定特定时间段后重复该功能的setInterval(function(){}, time)

    试试这个:

    $("#form").on("submit", function () {
        user = $("#username").val().length;
        if (user < 3 || user > 6) {
           $('#username').css('background', 'yellow'); //<---need to put it here
           setTimeout(function () {
               $('#username').css('background', 'white').focus(); //<--add focus too
           }, 3000);
           return false;
        } 
    }); 
    

    CHECKOUT THE DEMO FIDDLE

    This POST could help you.

    【讨论】:

    • 嘿,你在这里发现了一些问题。
    • 哈哈...我意识到为什么我的 userErrorBg 不在 if 语句中而且它仍然有黄色背景很奇怪....
    • 所以现在即使用户在 3-6 个字符内,bg 仍然会变黄......这真的没关系,因为提交页面后也会加载到其他页面,但我我只是好奇想了想再问:P
    • @user1850712 哦,是的,很好,但我修好了,你也可以取出小提琴链接。
    • 但我真的很好奇如果我将它放在 if 语句之外并且它在提交后被设置为变量...而不是告诉它在提交时运行它为什么会运行...
    【解决方案2】:

    您应该尝试使用setTimout() 而不是setInterval()。 setTimeout 被触发一次并且不会自行重复,您不需要像 setInterval 那样清除间隔。

    setTimout(function(){
        $('#username').css('background','white');
    },3000);
    

    【讨论】:

    • 我确实尝试了 setTimeout 但 bg 只是停留而不是在 3000 之后消失
    • 你必须在 setTimeout 函数中重置它,我已经更新了我的答案。
    【解决方案3】:

    试试这个..

    $("#form").on("submit",function(){
    
    
    user = $("#username").val().length; 
    
    
    if(user < 3 || user > 6)
    {
    
        setTimeout(function(){
            $('#username').css('background','yellow');
        },0);
    
        setTimeout(function(){
            $('#username').css('background','white');
        },3000);
    }
    
    });
    

    【讨论】:

      【解决方案4】:
      $("#form").on("submit",function(){
      

      试试这个-

      user = $("#username").val().length;
      userErrorBg = $('#username').css('background','yellow').delay(3000).css('background','white');
      
      
      if(user < 3 || user > 6)
      {
      
          setInterval("userErrorBg",0);
      
      }
      
      })
      

      【讨论】:

        猜你喜欢
        • 2010-11-16
        • 2013-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-01
        • 2013-08-30
        • 2011-11-11
        相关资源
        最近更新 更多