1 <!DOCTYPE html> 2 <head> 3 <meta charset="utf-8" /> 4 <title>无标题文档</title> 5 <style> 6 *{ 7 margin: 0; 8 padding: 0; 9 } 10 h1{ 11 text-align: center; 12 } 13 .box { 14 75px; 15 height: 48px; 16 position: relative; 17 line-height: 22px; 18 text-align: center; 19 display: block; 20 vertical-align: middle; 21 margin: 100px auto; 22 } 23 .txt{ 24 50px; 25 height: 45px; 26 line-height: 45px; 27 text-align: center; 28 border: 1px solid #ddd; 29 padding: 0; 30 float: left; 31 } 32 .control{ 33 float: left; 34 35 } 36 .btn { 37 22px; 38 line-height: 22px; 39 background-color: #eee; 40 border: 1px solid #ddd; 41 text-decoration: none; 42 color:#333; 43 display: block; 44 margin-left: -1px; 45 margin-bottom: -1px; 46 } 47 </style> 48 </head> 49 50 <body> 51 <h1>电商购买数量加减效果</h1> 52 <div class="box"> 53 <input type="text" value="1" class="txt" id="txt"> 54 <div class="control"> 55 <a class="btn" href="javascript:;" id="btn1">+</a> 56 <a class="btn" href="javascript:;" id="btn2">-</a> 57 </div> 58 </div> 59 </body> 60 </html> 61 <script type="text/javascript"> 62 // 功能需求: 63 // 1.当点击加号按钮时,购物车的数字会增加 64 // 2.当点击减号按钮时,购物车的数字会减少 65 // 作业注意: 66 // 1)数据类型检测与数据类型转换 67 // 2)数字减少的时候不能少于0 68 var txt = document.getElementById('txt'), 69 btn1 = document.getElementById('btn1'), 70 btn2 = document.getElementById('btn2'); 71 // 加号按钮添加事件 72 btn1.onclick = function () { 73 // console.log(typeof txt.value); 74 // txt.value++; 75 // 库存200 76 if( txt.value < 200){ 77 txt.value = parseInt(txt.value) + 1; 78 }else { 79 txt.value = 200; 80 } 81 // 点击加号就把鼠标指针换成小手状态 82 btn2.style.cursor = "pointer"; 83 } 84 85 btn2.style.cursor = "not-allowed"; 86 btn2.onclick = function () { 87 // 最小值应该是1 88 if(txt.value > 1){ 89 txt.value = parseInt(txt.value) - 1; 90 } 91 // 如果值等于1的时候,把鼠标指针换成不允许点击的样式 92 if(txt.value == 1 ){ 93 btn2.style.cursor = "not-allowed"; 94 } 95 96 } 97 </script>
主要要考虑:
(1).在+ 、- 时候出现的数量低于1或者高于库存量
(2).在减到1的时候,- 号的按钮会被设置成不能点击:
1 btn2.style.cursor = "not-allowed";