How do I set css using jQuery .css after a period of time?

佐手、 提交于 2020-01-05 04:15:11

问题


I couldn't figure out How to set time on jQuery .css property
I found one answer which is the closest to my question in jQuery change CSS after a certain amount of time

Here is my code:

<script>
    $(document).ready(function(){
        $("#homebutton,#title").click(function(){
            $("#title").css("font-size", "100%");  
            setTimeout(function(){ $("#title").css("font-size", "100%"); },2000)
        });
    });
</script>

I don't know what is wrong with that.
It seems like the solution I mentioned above doesn't work for me.

Thank you in advance guys

-----------------------------------------EDIT----------------------------------------------

Thanks for the response folks, there are several things that I want to re-explain:

  1. I initially set the font-size to 150% in my CSS, which mean through my jQuery, I expected it to change the font-size into 100%.
  2. I think I've misinterpreted the code, what I wanted to set is the time for decreasing gradually and not the timer

Basically, I want to change the font-size using jquery with transition, and not a sudden change


回答1:


The trouble is you first set font-size: 100% immediately, then you set it to the same value again after 2 seconds. Ie, you aren't changing the css.

To set the css value when clicked, and then set it to something else 2 seconds later, use different values in each call to .css(). Eg, to decrease the font size by half initially, then bring it back to normal size 2 seconds later:

$(document).ready(function(){
    $("#homebutton,#title").click(function(){
        $("#title").css("font-size", "50%");
        setTimeout(function(){ $("#title").css("font-size", "100%"); },2000);
    });
});

Edit: To gradually decrease the font size, you want to use .animate():

$(document).ready(function(){
    $("#homebutton,#title").click(function(){
        $("#title").animate({ "font-size": "50%" }, 2000);
    });
});

Demo: jsfiddle.net/Y6CrG/




回答2:


Change the font-size after the 2 second timeout. For example:

$("#title").click(function(){
  $("#title").css("font-size", "100%");  
  setTimeout(function(){ $("#title").css("font-size", "80%"); },2000)                               
});

I tried it in the following jsfiddle and it worked fine for me. http://jsfiddle.net/kianoshp/z9QeY/




回答3:


You can use this:

  $('#title').animate({fontSize : '100%'});

And If you want to set the duration You can use these

  $('#title').animate({fontSize : '100%'}, "slow");
  $('#title').animate({fontSize : '100%'}, "fast");


来源:https://stackoverflow.com/questions/14247054/how-do-i-set-css-using-jquery-css-after-a-period-of-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!