在文本框中输入文字,点击提交按钮或按回车键+Ctrl键实现将文字添加在页面上,并采用彩虹颜色的形式
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><div id="box"></div><input type="text" name="" id="txt"><input type="button" value="提交" id="btn"><script>//获取元素对象var oDiv=document.getElementById("box");var oTxt=document.getElementById("txt");var oBtn=document.getElementById("btn");//设置几种颜色var Color=['#0000ff','#c0c0c0','#ff0000','#00ff00'];function inputMessage(){var str=oTxt.value;var newStr='';var index=0;for(var i=0,len=str.length;i<len;i++){//把oTxt中的字符串加到newStr中newStr+='<span style=background:'+Color[index++%Color.length]+'>'+str.charAt(i)+"</span>";}//把newStr加到div中oDiv.innerHTML+=newStr;//清空文本框内容oTxt.value=null;} //点击提交按钮oBtn.onclick=function(){inputMessage();} document.onkeydown=function(evt){var e=evt||window.event;//按下Enter按键和Ctrl按键if(e.keyCode==13&&e.ctrlKey){inputMessage();}}</script>
</body>
</html>