Javascript - 每3秒更改一次文本和颜色

时间:2015-11-11 13:17:22

标签: javascript jquery text

我需要一些js代码的帮助。我搜索了其他主题,我尝试了一些代码,但它们没有用。我需要每3秒更换2个文本,第二个文本也需要更改颜色。

我使用了jquery代码,第一部分完成了,但我不知道如何做第二部分。

这是我的代码

<html>
<head>
<script src="js/jquery-2.1.4.min.js" type="text/javascript"></script>
<script>
$(function () {
    cuenta = 0;
    txtArray = ["TEXT1", "TEXT2"];
    setInterval (function () {
        cuenta++;
        $("#titulos").fadeOut(100, function () {
            $(this).text(txtArray [cuenta % txtArray.length]).fadeIn(100);
        });
    }, 3000);
});

</script>
<body>
<div>
<p id="titulos">TEXT1</p>
</div>
</body>
</html>

如何更改第二个数组的颜色?有没有其他方法可以使用纯js创建此代码,而不是使用jquery?

全部谢谢

4 个答案:

答案 0 :(得分:1)

试试这个

https://jsfiddle.net/33mbjjym/

var colors = ['blue', 'red', 'green', 'pink', 'yellow'];
var colorIndex = 1;
setInterval(function(){
    $('#titulos').css('color', colors[colorIndex]);
    if(colorIndex < colors.length)
        colorIndex += 1;
    else
        colorIndex = 1;
}, 3000);

答案 1 :(得分:1)

使用jQuery使用.css('rule-name', 'value').css({rule1: 'value', rule2: 'value'})

更改CSS

  $(function() {
    cuenta = 0;
    txtArray = ["TEXT1", "TEXT2"];
    setInterval(function() {
      cuenta++;
      $("#titulos").fadeOut(100, function() {
        $(this)
          .text(txtArray[cuenta % txtArray.length])
          .css('color', cuenta % 2 == 0 ? 'red' : 'blue')
          .fadeIn(100);
      });
    }, 3000);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <p id="titulos">TEXT1</p>
</div>

答案 2 :(得分:0)

你走了:

$(function () {
    cuenta = 0;
    txtArray = ["TEXT1", "TEXT2"];
    setInterval (function () {
        cuenta++;
        $("#titulos").fadeOut(100, function () {
            $(this).text(txtArray [cuenta % txtArray.length]).fadeIn(100);
            if(cuenta % txtArray.length == 1)
            {
                $(this).css("color","red");
            }
            else
             {
                $(this).css("color","black");
            }   
        });
    }, 3000);
});

答案 3 :(得分:0)

由于您使用的是JQuery,因此您可以使用css方法更改颜色,如下所示:

$(this).css("color", "red");

作为一个offtopic和个人推荐,我建议你用英语命名你的变量:)。