用JS中split方法實現彩色文字背景效果執行個體,jssplit

來源:互聯網
上載者:User

用JS中split方法實現彩色文字背景效果執行個體,jssplit

先來看看實現

效果實現步驟:

     1、擷取要用到的元素;

     2、聲明一個陣列變數(arrColor)存放顏色值;

     3、給按鈕添加點擊事件;

     4、擷取文字框的value值,並用split方法把文字框的字串值轉換成數組(arr)存放;

     5、迴圈取出存數組(arr)中的值並添加上span標籤;

     6、設定span標籤的背景色:從數組(arrColor)迴圈取值;

     7、把設定好的內容添加到div中;

效果完整代碼:

<!doctype html><html><head><meta charset="utf-8"><title>利用JS中split方法實現彩色文字背景效果執行個體</title><style>div { width:300px; height:200px; border:1px solid #333; background:#fff; padding:20px; line-height:40px; }span { padding:5px 15px; font-family:微軟雅黑; }</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="按鈕" /></body></html>

總結

用JS中split方法實現彩色文字背景效果執行個體到這就結束了,感興趣的朋友們可以自己動手操作看看,希望對大家的學習工作能有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.