javascript - 为什么这个滑块拖动的时候会闪
本文介绍了javascript - 为什么这个滑块拖动的时候会闪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
div id="a">
<div id="b"></div>
</div>
<style>
#a{
width:20px;
height:200px;
background-color:#aaa;
position:relative;
}
#b{
width:100%;
height:15%;
background-color:palevioletred;
position:absolute;
top:0px;
}
</style>
/------------------js部分------------------------- /
$(function(){
$("#b").mousedown(function(e){
var y0=e.offsetY;
var top0=parseInt($(this).css("top"));
$(document).bind('mousemove',event,movey);
$(document).mouseup(function(){
$(document).unbind("mousemove");
})
//定义鼠标拖动时执行的函数
function movey(){
var y1=event.offsetY;
var dis=y1-y0;
var bili=(dis+y0) / ( $("#a").height()-$("#b").height() )
if(bili>=0&&bili<=1)
$("#b").css("top",dis+top0);
else if (bili>1)
$("#b").css("top",$("#a").height()-$("#b").height());
else
$("#b").css("top","0px");
}
}).mouseup(function(){
$(document).unbind("mousemove");
})
})
问题是为什么鼠标拖拽滑块的时候,滑块会闪动,求大神指点
案例代码:https://jsfiddle.net/bbux0h7v/2/
解决方案
把offsetY
改成pageY
就行了。
关于offsetY
的意思,规范是这么写的:
The MouseEvent.offsetY read-only property provides the offset in the Y coordinate of the mouse pointer between that event and the padding edge of the target node.
关于pageY
的意思:
The MouseEvent.pageY read-only property returns the vertical coordinate of the event relative to the whole document.
你体会一下这两者的区别,然后再想想为什么offsetY
不行。
最后,个人觉得你的js代码写的有点乱……我稍微改了改,你可以参考下:
$(document).ready(function(){
let axiL = 0,
doc = $(document),
b = $("#b");
//定义鼠标拖动时执行的函数
function move(event){
const top = parseInt(b.css("top"));
let axiN = top + event.pageY - axiL;
axiN = (axiN < 0) ? 0: axiN;
axiN = (axiN > 170) ? 170: axiN;
b.css("top", axiN);
axiL = event.pageY;
}
b.on("mousedown", function() {
doc.on("mousemove", move);
axiL = event.pageY;
});
doc.on("mouseup", function() {
doc.off("mousemove", move);
});
});
这篇关于javascript - 为什么这个滑块拖动的时候会闪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文