背景
看了過時的資料,花費大把時間,不過也有收獲,還是寫寫吧!
分析
有同學可能想到直接在<textarea>標簽內輸入幫助文字,但是這又有一個新問題——因為<textarea>設置了默認內容,如果用戶不點擊輸入框(更改輸入框的文本),而直接提交,就把默認的提示內容提交到后台了。
參考其他同學的解決方案:創建一個div,這個div包含了幫助文字、<textarea>,並通過css的position屬性來控制,將幫助文字顯示到<textarea>中,點擊<textarea>(或提交)時,隱藏到幫助文字,這樣即使用戶不點擊輸入框直接提交,也不會把默認的提示文字提交到后台(因為幫助文字本身就與textarea不屬於同一個層)。
示例
實現代碼
<style> textarea { width: 200px; height: 200px; } div { width: 250px; display: inline-block; } .normal { border-right: solid 1px; } .normal small { color: #6da9a2; } .abnormal { position: absolute; margin-left: 40px; } #textArea { position: absolute; } .abnormal div { color: darkgrey; position: absolute; } </style> <h2>textarea添加幫助文字</h2> <hr/> <div class="normal"> <p><b>普通顯示方式</b></p> <textarea></textarea><br/> <!--代碼此處千萬不要強迫症發作——按回車鍵!!!不然就會在文本框內自動保留空格--> <small>*在此輸入備注信息</small> </div> <div class="abnormal"> <p><b>類似placeholder的顯示方式</b></p> <textarea id="textArea" onfocus="document.getElementById('introTxt').style.display='none'" onblur="if(value=='')document.getElementById('introTxt').style.display='inline'"></textarea> <!--代碼此處千萬不要強迫症發作——按回車鍵!!!不然就會在文本框內自動保留空格--> <div id="introTxt" onclick="focusTextarea()">在此輸入備注信息</div> </div> <script> /*這個函數是為了保證瀏覽者點擊introTextarea這層div時,使焦點自動移動到textarea*/ function focusTextarea() { document.getElementById('introTxt').style.display = 'none'; var temp = document.getElementById('textArea'); temp.focus(); } </script>
頁面效果
重點來了!!!![60B3CC894D449E931185900DDBDAE87E[5] 60B3CC894D449E931185900DDBDAE87E[5]](/image/aHR0cHM6Ly9pbWFnZXMyMDE1LmNuYmxvZ3MuY29tL2Jsb2cvMTAwNTA4Mi8yMDE2MTEvMTAwNTA4Mi0yMDE2MTEyOTIwNTkxNjY0Ni0yMTk5NTI1MjEucG5n.png)
可以這么說,我上面寫的你就當做沒看見吧!
因為
看到沒,我的親!
<textarea>新增屬性里面已經添加了placeholder屬性,也就是說,我上面寫了那么多,人家一句代碼搞定!
實現代碼
<textarea placeholder="這是幫助文字"> </textarea>
網頁效果
知識要更新!