写一个拖动的进度条
css样式就不写了 直接上js
思想就是 鼠标点击加号和减号 进度条改变宽度和margin来实现移动的效果 设置监听事件监听鼠标的左键和鼠标的移动
设置最大的移动距离 和最小的移动距离 $(document).off(“mousemove.drag”); 这里有个命名的方法 建议去差查一下 我这也说不太清楚
var max_masrgin = 401, move_x = 0, mouth_x = 0;//最大距离 移动距离 鼠标位置
//初始化位置 计算一开始进度条的位置
KaTeX parse error: Expected '}', got 'EOF' at end of input: …e_x = parseInt(("#scrollBar").css(“marginLeft”));
})
//给进度条绑定鼠标点击 和放开事件
$("#scroll_Thumb").on({
mousedown: function (e) {
mouth_x = event.pageX;
follower();
},
mouseup: function () { //清楚鼠标左键回位时事件 可以不要
$(document).off("mousemove.drag");
}
})
//清除移动
$(document).mouseup(function () { //鼠标可能有时候不在指定的位置 所以全局监听鼠标左键 放开
$(document).off("mousemove.drag");
})
//根居鼠标的移动计算进度条的位置
function follower() {
$(document).on({
'mousemove.drag': function (event) { .drag是给这个事件取一个名字 号之后清楚它
move_x = parseInt($("#scroll_Thumb").css("marginLeft"));
let x = event.pageX;
let instants = x - mouth_x;
if (instants > 0) {
move_x = move_x + instants
if (move_x < max_masrgin) {
change(move_x)
}
} else if (instants < 0) {
move_x = move_x + instants
if (move_x > 0) {
change(move_x)
}
}
mouth_x = x
}
});
}
每次点击按钮都要重新计算进度条的位置
function change(move_x) {
$("#scroll_Thumb").css("margin-left", move_x + "px") // 设置marging和width 因为进度条使用margon控制的
$("#scroll_Track").css("width", move_x + "px")
let number=Math.ceil(move_x/2)
$("#scrollBarTxt").text(number);
}
//减
$("#left").click(function () {
let value = parseInt($("#scrollBarTxt").text());
if (value > 1) {
value = value - 1;
change(value)
$("#scrollBarTxt").text(value)
}
})
//加
$("#right").click(function () {
let value = parseInt($("#scrollBarTxt").text());
if (value < 200) {
value = value + 1;
$("#scrollBarTxt").text(value)
change(value)
}
})