简体   繁体   English

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

[英]Javascript - Change text and color every 3 seconds

I need some help with a js code. 我需要有关js代码的帮助。 I've searched in other topics and i've tried some codes, but they didn't work. 我搜索了其他主题,并尝试了一些代码,但是它们没有用。 I need to change 2 text every 3 seconds and also the second text has to change their colour. 我需要每3秒更改2个文本,并且第二个文本也必须更改其颜色。

I used an jquery code, and the first part is done, but i don't know how to do the second. 我使用了一个jquery代码,并且第一部分已经完成,但是我不知道该怎么做。

This is my code 这是我的代码

<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>

How can I change the colour of the second array? 如何更改第二个数组的颜色? Is there any other way to make this code with pure js, not with jquery? 还有其他方法可以用纯js(而不是jquery)制作此代码吗?

Thanks for all 谢谢大家

try this 尝试这个

https://jsfiddle.net/33mbjjym/ 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);

To change CSS with jQuery use .css('rule-name', 'value') or .css({rule1: 'value', rule2: 'value'}) 要使用jQuery更改CSS,请使用.css('rule-name', 'value').css({rule1: 'value', rule2: 'value'})

  $(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> 

Here you go: 干得好:

$(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);
});

Since you are using JQuery, you can use the css method to change the color like this: 由于使用的是JQuery,因此可以使用css方法更改颜色,如下所示:

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

As an offtopic and personal recommendation, I'd suggest you to name your variables in English :). 作为建议和个人建议,我建议您使用英语:)来命名变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM