jQuery UI可调整大小的返回大小

1ft*_*tw1 1 javascript jquery jquery-ui jquery-plugins jquery-resizable

Hay即时消息是jquery的新手,我正在尝试使用可调整大小的代码。我可以使其正常工作,但似乎无法解决如何返回新尺寸的问题。我想将新大小设置为要保存在数据库中的php变量。我是javascript和jquery的新手,所以任何帮助都将是很大的帮助。

jyo*_*ore 5

可调整大小的插件本身不提供获取大小的方法。我认为他们没有实现这一点,因为它只是同一节点上的冗余方法,因为 jQuery 核心中已经有用于执行此操作的方法。

jQuery 提供了多种方法来查找宽度和高度,具体取决于您想要做什么。简单的宽度/高度方法获取 css 值。很多时候,使用outerWidth 和outerHeight 方法会更有用,但是,因为它们返回页面上元素的总计算大小,包括所有边距、边框等。

例子:

//Width/Height of just the element (as from css)
var w = $('.selector').width()
var h = $('.selector').height()

//Width/Height of total space the element takes up with formatting (includes border and margin)
var w = $('.selector').outerWidth()
var h = $('.selector').outerHeight()

//Width/Height of the space the content of the element takes up
var w = $('.selector').innerWidth()
var h = $('.selector').innerHeight()
Run Code Online (Sandbox Code Playgroud)

编辑将方法应用于可调整大小的事件

可调整大小的插件提供了几个要绑定的事件:创建、启动、调整大小和停止。我们可以绑定一个函数,以便在初始化时或之后的任何时间调用这些事件中的任何一个。听起来, start 事件在您开始调整元素大小时触发, stop 在您停止调整元素大小时触发,并且每次在调整大小(每个像素)期间元素的大小发生变化时都会调用 resize 。

初始化绑定:

$('.selector').resizable({
    //Other options
    create : function(event,ui) {...},
    start : function(event,ui) {...},
    stop : function(event,ui) {...},
    resize : function(event,ui) {...}
});
Run Code Online (Sandbox Code Playgroud)

或者以后随时绑定

$('.selector').bind('resizecreate',function(event,ui) {...});
$('.selector').bind('resizestart',function(event,ui) {...});
$('.selector').bind('resizestop',function(event,ui) {...});
$('.selector').bind('resize',function(event,ui) {...});
Run Code Online (Sandbox Code Playgroud)

现在,对于您的情况,我建议使用 2 个选项中的 1 个,要么绑定开始和停止命令以获取原始大小和修改后的大小,要么绑定以调整大小以实时处理该值。

开始/停止模式示例

var startW = 0;
var startH = 0;

$('.selector').resizable({
    //Other options
    start : function(event,ui) {
        startW = $(this).outerWidth();
        startH = $(this).outerHeight();
    },
    stop : function(event,ui) {
        endW = $(this).outerWidth();
        endH = $(this).outerHeight();
        alert("width changed:"+ (endW-startW) + " -- Height changed:" + (endH-endW));
    }
});
Run Code Online (Sandbox Code Playgroud)

移动到控制台时打印值的示例

$('.selector').resizable({
    //other options
    resize: function(event,ui) {
        console.log([$(this).outerWidth(),$(this).outerHeight()]);
    }
});
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助


ada*_*mer 5

在回答这些问题时,事情可能有所不同,但是现在jQuery UI使获取事件和ui元素的信息变得非常容易。我强烈建议控制台记录ui变量,因为那里有很多可用的信息。但是,要更好地回答您的问题:

$('.selector').resizable({
    stop: function (evt, ui) {
        console.log(ui.size);
    }
});
Run Code Online (Sandbox Code Playgroud)

应该产生具有高度和宽度属性的对象。这些是您可调整大小的项目的新高度和宽度

如果您想计算这两个值的差值,则可以引用,也可以在其中引用ui.originalSizeheight或width属性。

希望这比其他答案更简洁