每天学一个jquery插件-滚动条替换1

每天一个jquery插件-滚动条替换1

滚动条替换1

比如说原生的滚动条我不喜欢,但是我又不想写伪类样式,所以我需要弄一个替换物品,就是把滚动条隐藏了,然后自己整一个控制的dom用,今天只是计算了按钮的样式,很多参数是写死的,等有时间再补全

效果如下
在这里插入图片描述

代码部分

.rel{
    
    
	position: relative;
}
.box{
    
    
	width: 100%;
	height: 100%;
	position: absolute;
	background-color: red;
	opacity: 0.1;
	z-index:9;
}
.bar{
    
    
	background-color: lightgray;
	z-index: 8;
}
.xbar{
    
    
	width: 50%;
	height: 100%;
}
.ybar{
    
    
	width: 100%;
	height: 50%;
}
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>滚动条替换</title>
		<script src="js/jquery-3.4.1.min.js"></script>
		<script src="js/gdtth.js"></script>
		<link rel="stylesheet" href="css/gdtth.css" type="text/css" />
		<style>
			*{
     
     
				margin: 0px;
				padding: 0px;
				user-select: none;
			}
			#a{
     
     
				border: 1px solid lightgray;
				width: 200px;
				height: 40px;
				margin: 10px;
			}
			#b{
     
     
				border: 1px solid lightgray;
				width: 40px;
				height: 200px;
				margin: 10px;
			}
		</style>
	</head>
	<body>
		<div id="a"></div>
		<div id="b"></div>
	</body>
</html>
<script>
	$(function(){
     
     
		$("#a").gdtth("x",function(e){
     
     console.log("x滑块的移动距离"+e)})//横的
		$("#b").gdtth("y",function(e){
     
     console.log("y滑块的移动距离"+e)})//竖的
	})
</script>

$.prototype.gdtth = function(dir,func){
    
    
	var that =this;
	dir = dir==undefined?'y':dir;//渲染的目标
	$this = $(this);
	$this.addClass("rel")
	that.$bar = $("<div class='bar'></div>");//按钮效果
	$box = $("<div class='box'></div>");//触摸部分
	$box.appendTo($this);
	that.$bar.appendTo($this);
	var height = parseInt($box.height())/4;
	var width = parseInt($box.width())/4;
	var flag = flag;
	if(dir=='x'){
    
    
		that.$bar.addClass("xbar")
		$box.mousedown(function(){
    
    
			flag = true;
		}).mouseup(function(){
    
    
			flag = false;
		}).mouseleave(function(){
    
    
			flag=false;
		}).mousemove(function(e){
    
    
			if(flag){
    
    
				//计算底下按钮出现的正确位置
				var x = e.offsetX-width;
				x=x<0?0:x;
				x=x>(2*width)?(2*width):x;
				that.$bar.css("margin-left",x+"px");
				var per = x/100;
				if(func){
    
    
					func(per);
				}
			}
		})
	}else{
    
    
		that.$bar.addClass("ybar")
		$box.mousedown(function(){
    
    
			flag = true;
		}).mouseup(function(){
    
    
			flag = false;
		}).mouseleave(function(){
    
    
			flag =false;
		}).mousemove(function(e){
    
    
			if(flag){
    
    
				var y = e.offsetY-height;
				y=y<0?0:y;
				y=y>(2*height)?(2*height):y;
				that.$bar.css("margin-top",y+"px");
				var per = y/100;
				if(func){
    
    
					func(per);
				}
			}
		})
	}
}

思路解释

  • 就是想实现这样一个效果,把原生的滚动条隐藏起来,然后在我自己写的一个dom之中把基础功能实现了,将滚动条嵌入我指定的位置。
  • 所以我现在就是给定一个位置把滚动台做出来,然后完善回调,具体实现都在js代码里面打了注释了,没啥好讲的,溜了溜了
  • 完事,碎觉~

猜你喜欢

转载自blog.csdn.net/weixin_44142582/article/details/114239440