HTML + CSS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>案例:面向对象实现步进器</title>
<style>
.box {
margin-top: 100px;
text-align: center;
}
</style>
</head>
<body>
<div class="box"></div>
<div class="box1"></div>
<script src="./案例:面向对象实现步进器.js"></script>
<script>
var sp1 = new Stepper(
// 父元素
'.box',
{
// 左右两个标签的类型
ele: 'button',
// 中间标签的类型
textEle: 'span',
// 左右两边标签的值
lowValue: '-',
addValue: '+',
// 初始值
firstValue: 0
})
// 参数:步长
sp1.low(5)
sp1.add(5)
</script>
</body>
</html>
JS
function Stepper(ele, stepObj) {
// 拿到父元素
var faEle = document.querySelector(ele)
// 创建三个节点元素
this.lowBtn = document.createElement(stepObj.ele) || 'button'
this.addBtn = document.createElement(stepObj.ele) || 'button'
this.textBtn = document.createElement(stepObj.textEle) || 'span'
// 文字节点放入节点元素
this.lowBtn.appendChild(document.createTextNode(stepObj.lowValue))
this.addBtn.appendChild(document.createTextNode(stepObj.addValue))
this.textBtn.appendChild(document.createTextNode(stepObj.firstValue))
// 将节点元素放入页面
faEle.appendChild(this.lowBtn)
faEle.appendChild(this.textBtn)
faEle.appendChild(this.addBtn)
}
Stepper.prototype.low = function (step) {
// 获取步长
this.step = step
this.lowBtn.onclick = () => {
if (this.textBtn.innerHTML >= this.step) {
this.textBtn.innerHTML = +this.textBtn.innerHTML - this.step
}
}
}
Stepper.prototype.add = function (step) {
// 获取步长
this.step = step
this.addBtn.onclick = () => this.textBtn.innerHTML = +this.textBtn.innerHTML + this.step
}
效果: