鼠标拖动页面控件的重要技巧

以前做鼠标拖动控件移动的效果时,总是把几个事件并列申明,导致移动效果不好,一不小心就脱勾或卡住了,

经过js专业大神指点后,修改成如下结构,把document事件放到mousedown事件内部申明,效果立马就顺畅无比了,

真是术业有专攻啊。。。。

现记录下来,留作参考:

            chat.x = chat.y = chat.mousekey = 0;
            $('.chat_top').on("mousedown", function (event) {
                chat.mousekey = true;
                $('.chat_top').css("cursor", "move");
                var frame = $('.chat_frame');
                chat.x = event.pageX - parseInt(frame.css("left"), 10);
                chat.y = event.pageY - parseInt(frame.css("top"), 10);
                frame.fadeTo(20, 0.5);//点击后开始拖动并透明
                $(document).on('mousemove.chatMove', function (e) {
                    if (chat.mousekey) {
                        $('.chat_frame').css({ top: e.pageY - chat.y, left: e.pageX - chat.x });
                    }
                }).on('mouseup.chatUp', function () {
                    chat.mousekey = false;
                    $('.chat_top').css("cursor", "default");
                    $('.chat_frame').fadeTo("fast", 1);//松开鼠标后停止移动并恢复成不透明
                    $(document).off('mousemove.chatMove').off('mouseup.chatUp');
                });
            }).on('mouseup', function () {
                chat.mousekey = false;
                $('.chat_top').css("cursor", "default");
                $('.chat_frame').fadeTo("fast", 1);//松开鼠标后停止移动并恢复成不透明
                $(document).off('mousemove.chatMove').off('mouseup.chatUp');
            });

另外,对控件做半透明处理,也是增加拖动体验的一种方法,因为,控件内容很多很复杂的时候,拖动时浏览器要做大量的渲染运算,经常会很卡,而做出半透明效果再拖动,就不卡了。

这里我没有深究根源,猜测是半透明效果下,其实就是一张快照图片,拖动的是一个图片,因此不需要复杂的渲染和运算,

猜测是否正确,请知情的大侠赐教一二,谢谢!!

猜你喜欢

转载自blog.csdn.net/foren_whb/article/details/80334043