计数器
<style>
.step {
font-size: 0;
}
.step>button {
width: 17px;
height: 20px;
background-color: #F1F1F1;
border: 1px solid #cbcbcb;
outline: none;
text-align: center;
padding: 0;
margin: 0;
color: #232326;
}
.step>button:disabled {
color: #ccc;
cursor: not-allowed;
}
.step>input {
width: 46px;
height: 18px;
outline: none;
padding: 0;
margin: 0;
text-align: center;
border: 1px solid #cbcbcb;
border-left: none;
border-right: none;
}
</style>
<body>
<script type="module">
import SetpNumber from "./js/StepNumber.js"
var step = new SetpNumber();
step.addEventListener("change", changeHandler);
step.appendTo("body");
function changeHandler(e) {
console.log(e)
}
</script>
</body>
import Component from "./Component.js";
export default class StepNumber extends Component {
_step = 1;
constructor() {
super("div", "step");
this.elem.innerHTML = `
<button class='left'>-</button>
<input type='text'>
<button class='right'>+</button>
`
this.setStep(this._step);
this.elem.addEventListener("input", e => this.inputHandler(e));
this.elem.addEventListener("click", e => this.clickHandler(e));
}
inputHandler(e) {
if (e.target.nodeName !== "INPUT") return;
e.target.value = e.target.value.replace(/\D/g, "");
this.setStep(e.target.value);
this.dispatch();
}
clickHandler(e) {
if (e.target.nodeName !== "BUTTON") return;
if (e.target.className == "left") {
this.setStep(this._step - 1)
} else {
this.setStep(this._step + 1)
}
this.dispatch();
}
setStep(value) {
value = Number(value);
this.elem.children[0].disabled = false;
this.elem.children[2].disabled = false;
if (value <= 1) {
value = 1;
this.elem.children[0].disabled = true;
} else if (value >= 99) {
value = 99;
this.elem.children[2].disabled = true;
}
this._step = value;
this.elem.children[1].value = this._step;
}
dispatch() {
var evt = new Event("change");
evt.step = this._step;
this.dispatchEvent(evt);
}
}
购物车