我正在尝试构建一个简单的图像"click-n-drag"调整大小脚本。 我不想使用 jquery UI,因为它添加了很多额外的div,使文本混乱,并且需要额外的步骤来删除这些额外的div。
这个脚本有效,但是正如你会在小提琴中注意到的那样,它非常跳跃。
我一直在试图弄清楚如何获得它,以便它仅在鼠标"向下"(单击)时在鼠标移动时调整大小,并且在鼠标向上时停止调整大小并将变量重置回其原始起始位置。
提前谢谢。 很抱歉这里的格式草率,小提琴更干净。
从这里得到原始代码:原始来源我粘贴了原件,以便您可以清楚地了解它
这是jsfiddle:jsfiddle
jQuery.fn.extend({
resize: function(params){
var jQ = jQuery;
return this.each(function(){
var clicked = false; //set to off
var start_x; //starting point of mouse
var start_y;
if(params && params['target']){ var resize = params['target'];} //if target passed then use that
else{ var resize = this; }
if(params && typeof(params['y']) != "undefined"){ var y = params['y'];} //if y passed then fix the max height
else{ var y = 1;}
if(params && typeof(params['x']) != "undefined"){ var x = params['x'];} //if x then fix width
else{ var x = 1;}
if(params && typeof(params['min_width']) != "undefined"){ var min_w = params['min_width'];}
else{ var min_w = 1;}
if(params && typeof(params['min_height']) != "undefined"){ var min_h = params['min_height'];}
else{ var min_h = 1;}
$(this).hover(
function(){$(this).css('cursor', 'move');},
function(){$(this).css('cursor','default');clicked=false;}
);
$(this).mousedown(function(e){
clicked = true;
start_x = Math.round(e.pageX - $(this).eq(0).offset().left);
start_y = Math.round(e.pageY - $(this).eq(0).offset().top);
});
$(this).mouseup(function(e){clicked = false;});
$(this).mousemove(function(e){
if(clicked){
var mouse_x = Math.round(e.pageX - $(this).eq(0).offset().left) - start_x;
var mouse_y = Math.round(e.pageY - $(this).eq(0).offset().top) - start_y;
var div_w = $(resize).width();
var div_h = $(resize).height();
var new_w = parseInt(div_w)+mouse_x;
var new_h = parseInt(div_h)+mouse_y;
if(x==1 || (typeof(x) == "number" && new_w < x && new_w > min_w) ){ $(resize).css('width', new_w+"px"); }
if(y==1 || (typeof(y) == "number" && new_h < y && new_h > min_h) ){ $(resize).css('height',new_h+"px"); }
start_x = Math.round(e.pageX - $(this).eq(0).offset().left);
start_y = Math.round(e.pageY - $(this).eq(0).offset().top);
}
});
});
}
});
我发现,当您注意到的那样,将悬停和鼠标按下/鼠标向上事件都更改clicked
变量会使它有点跳跃。
我将其更改为使用dblclick()
选择图像,然后click()
取消选择,使功能更直观。所以我用以下方式替换了您$(this).hover (...
中的台词:
...
$(this).dblclick(function(e){
$(this).css('cursor', 'move');
clicked = true;
start_x = Math.round(e.pageX - $(this).eq(0).offset().left);
start_y = Math.round(e.pageY - $(this).eq(0).offset().top);
});
$(this).click(function(){
$(this).css('cursor','default');
clicked=false;
});
问题是,当鼠标离开图像时,$(this).mousemove(function(e){...函数停止,而是以窗口为目标,然后鼠标位置将更可预测:
$(window).mousemove(function(e){ ...
为了使它在需要时引用图像,我为此添加了一个新变量,image
.
我还用参数的点表示法清理了代码。
在这里查看我的工作编辑:http://jsfiddle.net/a3vYu/15/