Two days ago, I saw a small special effect in the input box of a website: the text is displayed one by one, and when it reaches the maximum length of the string, it will disappear one by one, and then it will reappear and disappear, displaying the string array in a circular way. I was a little curious about this special effect, so today I tried to write a simple demo with jquery, and finally finished the effect. First, let's see the effect after implementation:
Next, code.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Text is displayed one by one and disappears one by one</title> <script type="text/javascript" src="js/jquery-3.3.1.min.js"></script><!--Introduce jquery Plug-in unit --> <style type="text/css" rel="stylesheet"> #inputArea{ /*Simply set some properties of the input box */ margin: 30px; width: 300px; height: 50px; font-size: 20px; border: 1px solid #cccccc; } </style> </head> <body> <input id="inputArea" type="text"/> <script type="text/javascript"> let arr = ["yjry.com", "yjry.cn", "yjry.org", "yjry.xyz", "yjry.top"];//Define an array of strings to display let index = 0;//The displayed string index, which starts from the first string in the array by default let str = "";//Store the string to be displayed $input = $("#inputArea");//Obtain input Framed jquery object let timer1 = null;//Define two timers let timer2 = null; let endIndex1 = 1;//Define the index location of string truncation, two indexes for display and disappearance respectively let endIndex2 = 0; let flag = false;//Judge whether the current string is displayed completely $(function () {//dom Perform the operation after the tree is loaded, similar to but different from js Of window.onload timer1 = setInterval(add, 300);//Set two timers timer2 = setInterval(remove, 300); }); function remove() { if(flag === true){ clearInterval(timer1);//Clear the displayed timer str = arr[index];//Get the currently displayed string, and use another index to implement the loop disappearance endIndex1 = endIndex2; $input.val(str.substring(0, endIndex2--)); if(endIndex1 === 0){//If the current string disappears, then index Add one and set flag by falseļ¼Reset display timer index += 1; if(index === 5){//If the last string of the current index disappears, reset the index to 0 index = 0; } flag = false; timer1 = setInterval(add, 300); } } } function add() { if(flag === false){ str = arr[index]; endIndex2 = endIndex1; $input.val(str.substring(0, endIndex1++)); if($input.val().length === arr[index].length){//If all the current strings are displayed, set flag by true flag = true; } } } </script> </body> </html>
This method is completely personal. If there is any deficiency or optimization, welcome to communicate with me!