js/jquery 操作div 移动
发布网友
发布时间:2022-04-07 05:41
我来回答
共1个回答
热心网友
时间:2022-04-07 07:10
正好我最近 在搞 JQUERY 所以改写了个插件
调用:$(".x-movable").Drags({handler:".x-panel-header",zIndex:10000,opacity:0.7,direction:"x"});
你可以参考一下,以下是代插件码:
(function($) {
$.extend($.fn, {
getCss: function(key) {
var v = parseInt(this.css(key));
if (isNaN(v))
return false;
return v;
}
});
$.fn.Drags = function(opts) {
var obg=$(this)
var ps = $.extend({
zIndex: 20,
opacity: .7,
handler: null,
onMove: function() { },
onDrop: function() { }
}, opts);
var dragndrop = {
drag: function(e) {
var dragData = e.data.dragData;
dragData.target.css({
left:(ps.direction=="y")?(dragData.left):(dragData.left + e.pageX - dragData.offLeft),
top: (ps.direction=="x")?(dragData.top):(dragData.top + e.pageY - dragData.offTop)
});
dragData.onMove(e);
},
drop: function(e) {
var dragData = e.data.dragData;
dragData.target.css(dragData.oldCss);
dragData.onDrop(e);
$().unbind('mousemove', dragndrop.drag)
.unbind('mouseup', dragndrop.drop);
}
}
return this.each(function() {
var me = this;
var handler = null;
if (typeof ps.handler == 'undefined' || ps.handler == null){
handler = $(me);
}else{
handler = (typeof ps.handler == 'string' ? $(ps.handler, this) : ps.handle);
}
handler.bind('mousedown', { e: me }, function(s) {
var target = $(s.data.e);
var oldCss = {};
if (target.css('position') != 'absolute') {
try {
target.position(oldCss);
} catch (ex) { }
target.css('position', 'absolute');
}
oldCss.opacity = target.getCss('opacity') || 1;
var dragData = { //初始数据
left: oldCss.left || target.getCss('left') || 0,
top: oldCss.top || target.getCss('top') || 0,
width: target.width() || target.getCss('width'),
height: target.height() || target.getCss('height'),
offLeft: s.pageX,
offTop: s.pageY,
oldCss: oldCss,
onMove: ps.onMove,
onDrop: ps.onDrop,
handler: handler,
target: target
}
target.css('opacity', ps.opacity);
$().bind('mousemove', { dragData: dragData }, dragndrop.drag)
.bind('mouseup', { dragData: dragData }, dragndrop.drop);
});
});
}
})(jQuery);
调用说明:$(".x-movable").Drags({handler:".x-panel-header",zIndex:10000,opacity:0.7,direction:"x"});
其中$(".x-movable")是要被移动的DIV,".x-panel-header"是拖动手柄,科省略。 direction是移动方向,有"x"和"y"两个参数。
下面是我实际运用中更复杂的例子:
$(".x-layout-split-west").Drags({
zIndex:10000,
opacity:0.7,
direction:"x",
onDrop:function(e){
$(".x-layout-split-west").removeClass("x-splitbar-proxy")
var l=parseInt(e.data.dragData.target.css("left"))
if (l<ps.wmin){l=ps.wmin;}
if (l>ps.wmax){l=ps.wmax;}
ps.ww=l
ps.cl=l+ps.margins
ps.cw=w-ps.ew-ps.cl-ps.margins
$("#west").css({width:ps.ww});
//$("#west").css({left:l});
//$("#center .x-panel-body").css({width:ps.ch});
$("#center").css({width:ps.cw,left:ps.cl});
$(".x-layout-split-west").css("left",l)
}