jquery-11 留言板如何实现
一、总结
一句话总结:用live()方法让后面动态添加的元素也绑定之前对应类绑定的方法。
1、如何让后面动态添加的元素也绑定之前对应类绑定的方法?
用live()方法
91 $('.close').live('click',function(){ 92 $(this).parent().hide(1000); 93 });
2、如何给隐藏元素添加慢慢消失的特效?
给hide方法指定时间就好
92 $(this).parent().hide(1000);
3、如何去除元素的轮廓?
将outline属性置为none
31 textarea:focus{ 32 outline:none; 33 }
4、动态添加的标签如何有好看的样式?
添加类,在类中指定样式,不要在str中指定样式,这样太难写而且非常不清晰
84 str="<div class='show'>"; 85 str+="<div class='close'>×</div>";
52 .show{ 53 margin-top:20px; 54 border:2px solid #272822; 55 border-radius:10px; 56 height:50px; 57 } 58 59 .close{ 60 float: right; 61 margin-right:10px; 62 font-size:30px; 63 cursor: pointer; 64 }
5、如何给元素动态的添加标签?
append方法
83 val=$('textarea').val(); 84 str="<div class='show'>"; 85 str+="<div class='close'>×</div>"; 86 str+=val; 87 str+="</div>"; 88 $('.main').append(str);
二、live实现完整的留言板
3.事件委派
live();
die();
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>index</title> 6 <style> 7 *{ 8 font-family: 微软雅黑; 9 margin:0px; 10 padding:0px; 11 } 12 .main{ 13 width:1300px; 14 margin:0 auto; 15 } 16 17 .mess{ 18 margin-top:15px; 19 } 20 21 textarea{ 22 width:98%; 23 height:50px; 24 resize:none; 25 border-radius:20px; 26 padding:15px; 27 font-size:30px; 28 font-weight:bold; 29 } 30 31 textarea:focus{ 32 outline:none; 33 } 34 35 button{ 36 width:100px; 37 height:30px; 38 background: #272822; 39 font-weight: bold; 40 border:2px solid #ccc; 41 border-radius:10px; 42 color:#fff; 43 } 44 button:hover{ 45 border-color:#00f; 46 } 47 48 button:focus{ 49 outline:none; 50 } 51 52 .show{ 53 margin-top:20px; 54 border:2px solid #272822; 55 border-radius:10px; 56 height:50px; 57 } 58 59 .close{ 60 float: right; 61 margin-right:10px; 62 font-size:30px; 63 cursor: pointer; 64 } 65 </style> 66 <script src="jquery.js"></script> 67 </head> 68 <body> 69 <div class="main"> 70 <h1>小金留言板:</h1> 71 <div class='mess'> 72 <textarea></textarea> 73 </div> 74 <br> 75 <button>OK</button> 76 </div> 77 </body> 78 <script> 79 $('textarea').focus(function(){ 80 this.value=''; 81 }); 82 $('button').click(function(){ 83 val=$('textarea').val(); 84 str="<div class='show'>"; 85 str+="<div class='close'>×</div>"; 86 str+=val; 87 str+="</div>"; 88 $('.main').append(str); 89 }); 90 91 $('.close').live('click',function(){ 92 $(this).parent().hide(1000); 93 }); 94 </script> 95 </html>