jQuery - text color fade in

2019-06-27 04:00发布

I can't find a simple solution to this problem.

I am trying to fade in a color change for some text when there is an error from a button click.

if (document.getElementById("username").value == ""){ //First Name      
    $("#login_error").text("Please enetr a username!").css('color', '#FF0000');     
    $("#username_label").css('color', '#FF0000');fadeIn(3000);
}

I can get the color to change but it is instant. I am wanting to get the change of colour to fade in slowly.

Thanks Guys!

6条回答
孤傲高冷的网名
2楼-- · 2019-06-27 04:42

If you add jQuery UI, they added support for color animations.

Read http://jqueryui.com/demos/animate/ for details.

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

  <script>
  $(document).ready(function(){
    $(".block").toggle(function() {
      $(this).animate({ color: "#FF0000" }, 1000);
    },function() {
      $(this).animate({ color: "#000000" }, 1000);
    });
  });
  </script>

Update: jQuery now offers a color plugin to enable only this feature without including the entire jQuery-UI library.

查看更多
欢心
3楼-- · 2019-06-27 04:42

of course .css call is instant, and fadeIn is just chained (started after css is changed)

try using animate

查看更多
一纸荒年 Trace。
4楼-- · 2019-06-27 04:43

I find the method to change the color and found this

https://stackoverflow.com/a/15234173/1128331

already test and it work what I want to :)

查看更多
欢心
5楼-- · 2019-06-27 04:50

You can animate css properties using jQuery .animate function, i.e.

$(this).animate({ height: 250 });

BUT, you cannot animate color, sorry. For that you need to use plugin, see this answer for details.

Also, if you are using jquery UI, then it is possible:

Note: The jQuery UI project extends the .animate() method by allowing some non-numeric styles such as colors to be animated. The project also includes mechanisms for specifying animations through CSS classes rather than individual attributes.

(from http://api.jquery.com/animate/)

You have sample here.

查看更多
神经病院院长
6楼-- · 2019-06-27 05:00
The star\"
7楼-- · 2019-06-27 05:05

You need to use plugin, it's not part of the built in animation: https://github.com/jquery/jquery-color

Related question: jQuery animate backgroundColor

查看更多
登录 后发表回答