0
篇帖子
用vue实现一个可以长按加号/减号进行自增减的输入框: 思路:鼠标按下的时候启动一个定时器,控制值进行自增或者自减。当鼠标抬起的时候再取消这个定时器。
<!-- 可以长按加减号自增和自减 -->
<!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>Document</title>
<script src="./code/lib/vue-2.4.0.js"></script>
<style>
#app {
display: flex;
justify-content: center;
}
#input {
text-align: center;
}
</style>
</head>
<body>
<div id="app">
<button class="btn" @click="subtract()" @mousedown="startSubTimer()" @mouseup="endSubTimer()">-</button>
<input type="text" name="num" id="input" v-model="count">
<button class="btn" @click="add()" @mousedown="startAddTimer()" @mouseup="endAddTimer()">+</button>
</div>
</body>
<script>
var vm = new Vue({
el: "#app",
data: {
count: 0,
timer: null,
timer2: null,
},
methods: {
add: function () {
this.count++
},
subtract: function () {
if (this.count <= 0) {
this.count = 0;
} else {
this.count--;
}
},
autoAddStart: function () {
console.log(this.count)
this.timer2 = setInterval(() => {
this.count++
}, 200);
console.log("autoAddStart")
},
autoSubStart: function () {
if (this.count <= 0) {
this.count = 0
this.timer2 = null
} else {
this.timer2 = setInterval(() => {
if(this.count <= 0){
this.count = 0
}else {
this.count--
}
}, 200);
}
},
autoAddEnd: function () {
clearTimeout(this.timer2)
this.timer2 = null;
},
autoSubEnd: function(){
clearTimeout(this.timer2)
this.timer2 = null;
},
startSubTimer: function () {
this.timer = setTimeout(() => {
this.autoSubStart()
}, 1000);
console.log("mouseDown")
},
endSubTimer: function () {
clearTimeout(this.timer)
this.timer = null;
this.autoSubEnd()
console.log("mouseup")
},
startAddTimer: function () {
this.timer = setTimeout(() => {
console.log(this)
this.autoAddStart()
}, 1000);
},
endAddTimer: function () {
clearTimeout(this.timer)
this.timer = null;
this.autoAddEnd()
}
}
})
</script>
</html>
本博客内所有原创和翻译的文章的版权归本人所有,允许第三方转载,但转载时请务必保留作者名,并注明出处链接,否则本人将保留追究其法律责任的权利。
「人生在世,留句话给我吧」