slider-comp.js
1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
export default {
props: ["min", "max", "value"],
data() {
return {
slider: null, //滚动条DOM元素
thunk: null, //拖拽DOM元素
per: this.value || 0 //当前值
};
},
methods: {
initData() {
var _this = this;
this.$nextTick(() => {
_this.slider = _this.$refs.slider;
_this.thunk = _this.$refs.trunk;
if (_this.thunk) {
_this.thunk.onmousedown = function (e) {
var width = parseInt(_this.width);
var disX = e.clientX;
document.onmousemove = function (e) {
// value, left, width
// 当value变化的时候,会通过计算属性修改left,width
// 拖拽的时候获取的新width
var newWidth = e.clientX - disX + width;
// 拖拽的时候得到新的百分比
var scale = newWidth / _this.slider.offsetWidth;
_this.per = Math.ceil((_this.max - _this.min) * scale + _this.min);
_this.per = Math.max(_this.per, _this.min);
_this.per = Math.min(_this.per, _this.max);
_this.$emit("input", _this.per);
};
document.onmouseup = function () {
document.onmousemove = document.onmouseup = null;
};
return false;
};
}
});
}
},
//渲染到页面的时候
mounted() {
this.initData();
window.addEventListener('resize', () => {
this.initData();
}, false);
},
computed: {
// 设置一个百分比,提供计算slider进度宽度和trunk的left值
// 对应公式为 当前值-最小值/最大值-最小值 = slider进度width / slider总width
// trunk left = slider进度width + trunk宽度/2
scale() {
return (this.per - this.min) / (this.max - this.min);
},
width() {
if (this.slider) {
return this.slider.offsetWidth * this.scale + "px";
} else {
return 0 + "px";
}
},
left() {
if (this.slider) {
return (
this.slider.offsetWidth * this.scale -
this.thunk.offsetWidth / 2 +
"px"
);
} else {
return 0 + "px";
}
}
}
};