<style type="text/css"> textarea{ width: 400px; height:400px; resize: none; } .limit{ width: 400px; text-align: right; } #d1{ margin: 100px; } input::-webkit-input-placeholder{ color:red; } input::-moz-placeholder{ /* Mozilla Firefox 19+ */ color:red; } input:-moz-placeholder{ /* Mozilla Firefox 4 to 18 */ color:red; } input:-ms-input-placeholder{ /* Internet Explorer 10-11 */ color:red; } textarea::-webkit-input-placeholder{ color:red; } textarea::-moz-placeholder{ /* Mozilla Firefox 19+ */ color:red; } textarea:-moz-placeholder{ /* Mozilla Firefox 4 to 18 */ color:red; } textarea:-ms-input-placeholder{ /* Internet Explorer 10-11 */ color:red; } </style>
2、文本框字數限制
<div id = "d1"> <div> <input type="text" placeholder='的奇偶為不讓你'/> <textarea placeholder='減肥的設計費我沒如風達'/> </div> <div class="limit"> 最大可輸入 <span>0</span>/20 </div> </div> <script type="text/javascript"> //先定義計算字符串字數 function getStrleng(str,max) { myLen = 0; i = 0; for (; (i < str.length) && (myLen <= max * 2); i++) { if (str.charCodeAt(i) > 0 && str.charCodeAt(i) < 128) //根據Unicode編碼值判斷是否漢字 myLen++; else myLen += 2; } return myLen; } //定義函數獲得DOM元素 function Q(s){ return document.querySelector(s); } //定義函數顯示寫了幾個字 function checkWord(c) { var maxstrlen = 20; var str = c.value; //對象的內容 myLen = getStrleng(str,maxstrlen); //計算str的字符個數 var wck = Q(".limit span"); console.log(wck) if(myLen > maxstrlen * 2){ c.value = str.substring(0, i - 1); }else{ wck.innerHTML = Math.floor(myLen / 2); } } Q('textarea').onkeyup =function(){ checkWord(this); } </script>