Text change when background colour changes using Javascript

左心房为你撑大大i 提交于 2019-12-13 09:48:22

问题


Below is my Javascript for changing the background colour of a website, however is there a way to change text in the body of the page when this change in colour occurs?

function changeColor(element, curNumber){
curNumber++;

if(curNumber > 4){
    curNumber = 1;
}
console.log(curNumber);
element.addClass('color' + curNumber, 500);
// So previous classes get removed.
element.attr('class', 'color' + curNumber);
setTimeout(function(){changeColor(element, curNumber)}, 1000);  
}
changeColor($('#testElement'), 0);

回答1:


Simply have the text in an array, ( get it from some elements using jquery - however you want it) iterate through it and change the content inside the div using html() function when you are changing the color.

Simple modification of your code would be something like

function changeColorAndText(element, curNumber){
 curNumber++;
 if(curNumber > 4){
    curNumber = 1;
 }
 element.addClass('color' + curNumber, 500);
 element.html(arr[curNumber]);
 element.attr('class', 'color' + curNumber);
 setTimeout(function(){changeColorAndText(element, curNumber)}, 1000);  
}
var arr = ['hi','hello ','how ','are ','you '];
changeColorAndText($('#testElement '), 0);

JSFiddle



来源:https://stackoverflow.com/questions/23226476/text-change-when-background-colour-changes-using-javascript

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