Let's take a look at the implementation diagram first
Effect implementation steps:
1. Get the elements to be used;
2. Declare an array variable ( arrColor ) to store color values;
3. Add click event to the button;
4. Get value value of the text box and use the split method to convert the string value of the text box into an array ( arr ) and store it;
5. Loop out the value in the stored array ( arr ) and add span tag;
6. Set the background color of the span label: loop the value from the array ( arrColor );
7. Add the set content to div ;
The effect complete code:
<!doctype html><html><head><meta charset="utf-8"><title>Example of using split method in JS to achieve colored text background effect</title><style>div { width:300px; height:200px; border:1px solid #333; background:#fff; padding:20px; line-height:40px; }span { padding:5px 15px; font-family: Microsoft Yahei; }</style><script>window.onload = function(){ var oDiv=document.getElementById('div1'); var aInp=document.getElementsByTagName('input'); var arrColor = ['#f00','#ff0','#f0f','#0ff']; aInp[1].onclick=function(){ var str = aInp[0].value; var arr = str.split(''); for(var i=0; i<arr.length; i++ ){ arr[i]='<span style="background:'+arrColor[i%arrColor.length]+'">'+arr[i]+'</span>'; } oDiv.innerHTML += arr.join(''); }}</script></head><body><div id="div1"> </div><input type="text" /><input type="button" value="button" /></body></html>Summarize
The example of using the split method in JS to achieve colored text background effect is over. Interested friends can do it by themselves, hoping it will be helpful to everyone's study and work.