js實作點擊標籤文字,文字出現在文字方塊裡,下面2種方法實現的功能略有不同,整體來說方法一功能更強大。
第一種方法:隨意點擊任何標籤都會出現在文字方塊中,如何第二次點擊標籤,對應的文字就會在文字方塊中消失。
1 2 3 4 5 6 7 8 9 10 11 | <style>.c{ width:40px; height:25px; line-height:25px; text-align:left; margin:2px; float:left; font-size:12px; cursor:pointer }</style>
<input id= "i" type= "text" ><div class = "c" id= "c0" >市级,</div><div class = "c" id= "c1" >省级,</div><div class = "c" id= "c2" >国家级
<script>
var x=[ "市级" , "省级" , "国家级" ];
var y=[];
function $(id){ return document.getElementById(id)};
for ( var i=0,m=x.length;i<m;i++){$( "c" +i).onclick=( function (i){ return function (){
var s=y.join( "," ).indexOf(x[i]); if (s>=0){
for ( var r in y){ if (y[r]==x[i]){y.splice(r,1)}}}
else {y.push(x[i])}$( "i" ).value=y.join( " " );}})(i)}
</script>
|
登入後複製
效果圖:

第二種方法:當點擊「腳本之家」標籤的時候,此標籤就出現在了文字方塊裡,再點擊SQL標籤後,「SQL」標籤就會替換掉「腳本之家”標籤出現在文字方塊中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <style>.label {cursor:pointer}</style>
<input type= "text" id= "textbox" size = "30" name= "chaxinmd" />
<span class = "label" >JS特效</span>
<span class = "label" >C++</span>
<span class = "label" >SQL</span>
<span class = "label" >脚本之家</span>
<script type= "text/javascript" >
spans=document.getElementsByTagName( "span" );
for (i=0;i<spans.length;i++)
{ if (spans[i].className== "label" )
{ spans[i].onclick= function ()
{ document.getElementById( 'textbox' ).value=this.innerHTML;
}}}
</script>
|
登入後複製
效果圖:

這裡再為大家分享另一個Javascript的小技巧-----JS實作點擊文字方塊清除表單內部默認文字,有時大家在填寫表單內容時,表單裡會出現一些默認提示文字,我們又不想一個個刪除,有什麼辦法可以實現快速清除?以下是我為大家準備的小程式碼:
1 2 3 4 5 6 7 8 9 | <form action= "" method= "get" name= "so_box" id= "so_box" >
<input name= "so_name" type= "text" id= "so_name" onFocus= "if(value==defaultValue){value='';}"
onBlur= "if(!value){value=defaultValue;}"
value= "请输入的关键词" >
<input type= "submit" name= "Submit" value= "提交" onFocus= "if(so_box.so_name.value==so_box.so_name.defaultValue){so_box.so_name.value='';}" >
</form>
|
登入後複製
效果圖:

點選文字方塊之後

以上就是本文的全部內容,希望對大家的學習有所幫助。