知识有两种,一种是你知道的,一种是你知道在哪里能找到的!
无言博客
一个菜鸟程序员,在复制粘贴的道路上越走越远!!!
JS实现slider滑块(兼容PC和WAP)
无言博客 418 2020-3-29

有时候做音乐或者视频播放器的时候需要用到进度条

虽然video或者audio标签自带就有

但每个浏览器的样式都不一样

所以就需要我们自己写一个

演示:

value:0

value:0

话不多说,下面是代码,样式大家自行修改


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
<title>slider</title>
<script src="https://libs.baidu.com/jquery/2.1.1/jquery.min.js"></script>
<style>
body{ margin:0; background-color:#0f0f0f; color:white; text-align:center;}
.slider{ margin:80px auto 50px;padding:10px 15px; max-width:800px;}
</style>
</head>
<body>
<div class="slider" id="slider"></div>
<p>value:<span id="value">0</span></p>
<div class="slider" id="slider2"></div>
<p>value:<span id="value2">0</span></p>
<script>
$.Slider = function(view,callback){
	var div = '<style>.track{width: 100%;height: 2px;background-color: #fff;position: relative;}.buffered{background-color: rebeccapurple;height: inherit;width:0;}.thumb{height: inherit;background-color: cyan;position: absolute;top: 0;width:0;max-width:100%;}.thumb:before{content:"";position: absolute;width: 14px;height: 14px;border-radius: 50%;background-color: white;right: -7px;top: 50%;margin-top: -7px;}</style><div class="track"><div class="buffered"></div><div class="thumb"></div></div>';
	$(view).html(div);
	var startX,moveX,endX,state=false;
	var touchEvents = {
		touchstart: "touchstart",
		touchmove: "touchmove",
		touchend: "touchend",
		initTouchEvents: function(){
			if(!isMobile()){
				this.touchstart = "mousedown";
				this.touchmove = "mousemove";
				this.touchend = "mouseup";
			}
		}
	};
	touchEvents.initTouchEvents();
	$(view)[0].addEventListener(touchEvents.touchstart, function(e) {
		startX = e.pageX?e.pageX:e.changedTouches[0].pageX;
		state=true;
	});
	$(view)[0].addEventListener(touchEvents.touchmove, function(e) {
		if(!state)return;
		moveX = e.pageX?e.pageX:e.changedTouches[0].pageX;
		var trackL = $(view+' .track').offset().left;
		var trackW = $(view).width();
		var thumbW = (moveX-trackL)/trackW*100;
		$(view+' .thumb').css('width',thumbW+"%");
		if(thumbW >= 100){
			endX = 100;
		}else if(thumbW <= 0){
			endX = 0;
		}else{
			endX = Math.round(thumbW);
		}
	});
	$(view)[0].addEventListener(touchEvents.touchend, function(e) {
		state=false;
		if (typeof callback === "function") {
			if(endX)callback(endX);
		}
	});
	function isMobile(){
		if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
			return true;
		}else{
			return false;
		}
	}
}

/*调用*/
$.Slider("#slider",function(e){
	$("#value").html(e);
});
$.Slider("#slider2",function(e){
	$("#value2").html(e);
});
</script>
</body>
</html>


喜欢就点赞留言吧!!!

END
留言
无言博客
2020-08-05 14:59
好用

发表评论: