jQuery Manual Resizable DIV

天大地大妈咪最大 提交于 2020-01-12 08:47:11

问题


I'm trying to create a resizable div without using jQuery's interface library.

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>  

The first resize works fine(i.e. mousedown, mousemove then mouseup), but on subsequent (mousedown+mousemove)s, the browser attempts to drag the whole resizeBar div instead of properly resizing its parent container. On mouseup, the div then starts resizing "cooldiv" on mousemove without any mousedown required, until a further click of the mouse.

These problems don't show up in Internet Explorer.


回答1:


Try adding

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

to the end of your mouseup function.




回答2:


i was occasionally able to break the resize functionality, where i would get the "not allowed" cursor and the box would not dynamically resize, although when i let go of the mouse it would resize appropriately and stay that way.

adding return false; to the end of the resize function seems to stop the browser from trying to select/drag the resize bar. i'm working in a limited environment so i can only test with ie8 (and ie8 in ie7 mode).

i had to replace your calls to $() with $(document) to get this working. i would also recommend moving the mousemove binding out of the mousedown handler, and removing the unbinding call.




回答3:


This is an example with a "hr" tag as separator (between 2 divs):

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

Javascript: (using 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 (optional):

hr {
    background-color: #DDD;
    border: 1px solid #AAA;
    cursor: n-resize;
    height: 10px;
}


来源:https://stackoverflow.com/questions/527468/jquery-manual-resizable-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!