最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to add a CSS attribute just for specific time via JQuery (revert back to normal after 2 sec) - Stack Overflow

programmeradmin1浏览0评论

I want to set a CSS attribute for a element (div) just for 2 sec. here is my try:

html:

<div class="div">foo</div>
<input class="btn" type="button" value="click" />

jquery:

$(".btn").click(function(e) {
   $(".div").css({"border": "1px solid #ccc"});
});

But the above code will be applied for ever, how can I limit it for a specific period ?

I want to set a CSS attribute for a element (div) just for 2 sec. here is my try:

html:

<div class="div">foo</div>
<input class="btn" type="button" value="click" />

jquery:

$(".btn").click(function(e) {
   $(".div").css({"border": "1px solid #ccc"});
});

But the above code will be applied for ever, how can I limit it for a specific period ?

Share Improve this question edited Aug 6, 2015 at 13:48 Shafizadeh asked Aug 6, 2015 at 8:59 ShafizadehShafizadeh 10.4k15 gold badges58 silver badges92 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

I think using css class maybe the best solution just because i don't know the prev border style or the others css rules applied to the element:

css

.borderStyle{
    border: 1px solid #ccc!important;
}

js

$('.btn').click(function(){
    $('.div').addClass("borderStyle");
    setTimeout(function(){ $('.div').removeClass("borderStyle"); }, 2000);
});

toggle class version

$('.btn').click(function(){
    $('.div').toggleClass("borderStyle");
    setTimeout(function(){ $('.div').toggleClass("borderStyle"); }, 2000);
});

fiddle

don't know why the toggleclass don't work for you but lets keep it shown in my answer for future reviews

I think you could use something like this :

$(".btn").click(function(e) {
    $(".div").css({"border": "1px solid #ccc"});
    setTimeout(function(){
        $(".div").css({/* Your initial css */});
    }, 2000);
});

Pretty simple, add a setTimeout() and let that run after 2 seconds and let it remove the border.

$(".btn").on("click", function() {
    $('.foo').css('border', '1px solid #ccc');
    setTimeout( function() { 
        $('.foo').css('border', 'none');
    }, 2000);
});

Working JSFIDDLE

As you can see, I have replaced your .click() with .on(). Read here why it's better to use .on() and here how you use it.

After two seconds to remove css atribute:

$(".btn").click(function(e) {
   $(".div").css({"border": "1px solid #ccc"});
   setTimeout(function() { 
       $(".div").css({
           'border' : 'none',
           'width' : '30px',
           'top' : '10px',
           'left' : '30px',
           'bottom' : '10px',
           'right' : '30px'
       });
   }, 2000);
});

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论