代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>购物车加减操作</title> <style> div { width: 80px; } input[type='text'] { width: 50px; height: 44px; outline: none; border: 1px solid #ccc; text-align: center; border-right: 0; } input[type='button'] { height: 24px; width: 22px; cursor: pointer; } input { float: left; border: 1px solid #ccc; } </style> </head> <body> <div> <!-- readonly 布尔值。存在时表示控件的值不可编辑 --> <input type="text" id="total" value="1" readonly /> <input type="button" value="+" id="add" /> <input type="button" value="-" id="reduce" disabled /> </div> <script> let total = document.querySelector('#total') let add = document.querySelector('#add') let reduce = document.querySelector('#reduce') add.addEventListener('click', function(){ // console.log('okj') total.value++ // total.value自动转为数字类型 自身自增 // total.value += 1 会出现问题,total.value是字符串 +只会在1后面拼接1 不会相加 // 解除减号不可点击状态 reduce.disabled = false }) reduce.addEventListener('click', function () { // console.log('okj') total.value-- if(Number(total.value) === 1){ reduce.disabled = true } }) </script> </body> </html>
效果图:
web API-事件基础-购物车加减操作
最新推荐文章于 2024-11-03 16:40:52 发布