加减 script函数初识
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style> 7 body{ 8 margin: 0; 9 } 10 .c1{ 11 top: 10px; 12 left: 10px; 13 position: relative; 14 width: 150px; 15 height: 22px; 16 border: 1px solid black; 17 padding-right: -22px; 18 } 19 .c2{ 20 position: absolute; 21 width: 22px; 22 height: 22px; 23 24 line-height: 22px; 25 text-align: center; 26 background-color: #dce7f4; 27 border-right: 1px solid black; 28 cursor: pointer; 29 } 30 .c3{ 31 32 } 33 .c3 input{ 34 border: 0; 35 padding: 0; 36 position: absolute; 37 left: 23px; 38 width: 104px; 39 height: 22px; 40 line-height: 22px; 41 text-align: center; 42 43 44 } 45 46 .c4{ 47 right: 0; 48 position: absolute; 49 width: 22px; 50 height: 22px; 51 line-height: 22px; 52 text-align: center; 53 border-left: 1px solid black; 54 background-color: #dce7f4; 55 cursor: pointer; 56 } 57 58 </style> 59 </head> 60 <body> 61 <div class="c1"> 62 <div class="c2" onclick="Minus()">-</div> 63 64 <div class="c3"> 65 <input type="text" id="count" value="0" /> 66 </div> 67 68 <div class="c4" onclick="Plus()">+</div> 69 </div> 70 <script type="text/javascript"> 71 //定义函数 72 function Plus() { 73 var old_str = document.getElementById('count').value; 74 try{ 75 var old_int = parseInt(old_str); 76 }catch(e){ 77 var old_int = 1 78 } 79 var new_int = old_int + 1; 80 document.getElementById('count').value = new_int; 81 } 82 function Minus() { 83 var old_str = document.getElementById('count').value; 84 try{ 85 var old_int = parseInt(old_str); 86 }catch(e){ 87 var old_int = 1 88 } 89 var new_int = old_int - 1; 90 document.getElementById('count').value = new_int; 91 } 92 </script> 93 </body> 94 </html>