鼠标移动时将鼠标光标保持在手柄上

Keeping mouse cursor over the handle when mouse moves

本文关键字:鼠标 移动 光标      更新时间:2023-09-26

我在这里构建了一个简单的表列调整器:

http://jsfiddle.net/44k6c/

我不能为此使用插件,但我需要模仿这个插件中的功能:

http://quocity.com/colresizable/

我已经设法很好地调整了列的大小,但我的光标被允许离开手柄(第 x 中的灰色框)。我需要以某种方式约束光标,以便在鼠标移动时它停留在手柄上。我已经查看了上面插件的源代码,但它没有阐明如何实现这一目标。

我的js代码正在进行中,目前相当粗糙:

 $(document).ready(function () {
                var th,
                    previousColIndex,
                    nextColIndex,
                    previousColWidth,
                    nextColWidth,
                    thWidth,
                    currentXPos;
                $('.resize').mousedown(function(e) {
                     currentXPos = e.pageX; 
                     th = $(this).parent();
                     nextColIndex = th.index() + 1;
                     nextColWidth = $('table tr th').eq(nextColIndex).width();
                     thWidth = th.width();
                     $(document).bind('mousemove',function(e){
                         if(e.pageX < currentXPos) {
                            thWidth = thWidth - 1;
                            nextColWidth = nextColWidth + 1;
                            $('table tr td').eq(th.index()).css({'width': thWidth + 'px'});
                            th.css({'width':thWidth + 'px' });
                            $('table tr td,table tr th').eq(nextColIndex).css({'width': nextColWidth  + 'px'});
                            currentXPos = e.pageX; 
                         } else {
                            thWidth = thWidth + 1;
                            nextColWidth = nextColWidth - 1;
                            $('table tr td').eq(th.index()).css({'width': thWidth + 'px'});
                            th.css({'width':thWidth + 'px' });
                            $('table tr td,table tr th').eq(nextColIndex).css({'width': nextColWidth  + 'px'});
                            currentXPos = e.pageX; 
                         }

                     })
                }).mouseup(function(){

$(document).unbind('mousemove');

})
    $(document).mouseup(function() {
    $(document).unbind('mousemove');
 })
 })

这个 jsFiddle 能解决问题吗?

您可能在以下行中遇到了问题:

thWidth = thWidth - 1;
nextColWidth = nextColWidth + 1;

它可能应该是:

thWidth = thWidth - currentXPos + e.pageX;
nextColWidth = nextColWidth + currentXPos - e.pageX;

编辑:链接错误。使用这个:http://jsfiddle.net/44k6c/4/