javascript - 为什么这个滑块拖动的时候会闪
PHP中文网
PHP中文网 2017-04-11 12:25:50
[JavaScript讨论组]
p id="a">
    

/------------------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/

PHP中文网
PHP中文网

认证0级讲师

全部回复(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);
    });
});
PHPz

不懂,可以百度下滑动块的实现对比下

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号