4

我正在尝试在不使用 jQuery 的界面库的情况下创建一个可调整大小的 div。

var myY = 0;
var mouseDown = false;
var originalHeight = 0; 

function resize(e){
    if(mouseDown == true){
        $("#cooldiv").height(originalHeight+e.pageY-myY);
    }
} 

$(document).ready(function(){
    $().mouseup(function(e){
        myY = 0;
        mouseDown = false;
        originalHeight = 0;
        $().unbind("mousemove", resize);
    });

    $("#resizeBar").mousedown(function(e){
        myY = e.pageY;
        originalHeight = $("#cooldiv").height();
        mouseDown = true;
        $().bind("mousemove", resize);
    });
});

...

<div id="cooldiv" style="width: 500px; height: 300px; background-color: #cccccc; position: relative;">
<div id="resizeBar" style="height: 10px; width: 500px; background-color: #aaaaaa; position: absolute; bottom: 0;"></div>
</div>  

第一次调整大小可以正常工作(即 mousedown、mousemove 然后 mouseup),但在随后的 (mousedown+mousemove) 上,浏览器会尝试拖动整个 resizeBar div,而不是正确调整其父容器的大小。在 mouseup 上,div 然后开始在 mousemove 上调整“cooldiv”的大小,而不需要任何 mousedown,直到再次单击鼠标。

这些问题不会出现在 Internet Explorer 中。

4

3 回答 3

1

尝试添加

$("#cooldiv").focus();

到 mouseup 函数的末尾。

于 2009-04-08T19:18:25.537 回答
1

这是一个使用“hr”标签作为分隔符的示例(在 2 个 div 之间):

<div>Text here</div>
<hr />
<div>Other text</div>

Javascript:(使用 JQuery):

var hr = null;
$("hr").mousedown(function(e) {
    hr = {
        y : e.pageY,
        p : $(this).prev(),
        n : $(this).next(),
        ph: $(this).prev().height(),
        nh: $(this).next().height()
    };
    e.preventDefault();
});
$(document).mousemove(function(e) {
    if(hr) {
        hr.p.height(hr.ph+(e.pageY - hr.y));
        hr.n.height(hr.nh-(e.pageY - hr.y));
    }
    e.preventDefault();
}).mouseup(function(e) {
    hr = null;
    e.preventDefault();
});

CSS(可选):

hr {
    background-color: #DDD;
    border: 1px solid #AAA;
    cursor: n-resize;
    height: 10px;
}
于 2010-12-20T06:36:36.253 回答
1

我偶尔能够打破调整大小的功能,在那里我会得到“不允许”光标并且框不会动态调整大小,尽管当我放开鼠标时它会适当地调整大小并保持这种状态。

添加return false;resize函数的末尾似乎可以阻止浏览器尝试选择/拖动调整大小栏。我在有限的环境中工作,所以我只能使用 ie8(以及 ie7 模式下的 ie8)进行测试。

我不得不将您的电话替换为$()$(document)使其正常工作。我还建议将mousemove绑定移出mousedown处理程序,并删除解除绑定调用。

于 2010-08-09T16:02:30.763 回答