繁体   English   中英

jQuery调整大小事件处理程序,在调整大小之前捕获特定元素的原始宽度和高度

[英]jQuery resize event handler, capture the original width and height of a certain element before resize

我有以下代码,它可以工作,但我讨厌它:),我想做些更清洁的东西。

这个想法是:-我向窗口对象添加了一个调整大小事件处理程序; -当... doneResizing函数启动并调用方法时,我使用setTimeout来让代码等待用户完成调整大小的操作- 确切地说是Canvas.resize()方法。

我在这里做错的地方是: 我需要捕获“画布”元素的原始宽度和高度,以及调整大小后该元素的“宽度”和“高度”。

现在,我正在使用全局变量(在另一个作用域中使用全局变量,这无关紧要),您知道一种更好的方法吗?

function doneResizing() {
    if (Canvas.isInitialized()) {
        $timeout(function() {
            var cw = element.width();
            var ch = element.height();
            // Resize the svg.
            $('#canvas svg').width(cw);
            $('#canvas svg').height(ch);
            Canvas.resize(iw, ih, cw, ch, $('#canvas'), $('#canvas svg'));
            iw = null;
            ih = null;
        }, 10);
    }
};

var id;
var iw, ih;
$(window).resize(function(event) {
    clearTimeout(id);
    if (!iw) iw = element.width();
    if (!ih) ih = element.height();
    element.addClass('loading');
    $('#canvas svg').hide();    
    id = setTimeout(doneResizing, 500);    
});

谢谢!

我阅读的要求是:

  • 您需要记录初始大小, 然后再开始调整大小,因为一旦开始调整大小,您将无法准确知道原始大小。
  • 您需要忽略多个调整大小,直到用户停止调整大小为止,因此时间延迟是适当的,但是如果进来另一个调整大小,则需要清除计时器。
  • 您不需要第二个setTimeout。

您已经完成了大部分操作,因此需要进行一些调整:

var id;
// record the initial size
var iw = element.width();
var ih = element.height();

$(window).resize(function (event) {
    clearTimeout(id);
    element.addClass('loading');
    $('#canvas svg').hide();
    id = setTimeout(doneResizing, 500);
});

function doneResizing() {
    if (Canvas.isInitialized()) {
        var cw = element.width();
        var ch = element.height();
        // Resize the svg.
        $('#canvas svg').width(cw);
        $('#canvas svg').height(ch);
        Canvas.resize(iw, ih, cw, ch, $('#canvas'), $('#canvas svg'));
        // Now record the last position as the new start size
        iw = cw;
        ih = ch;
    }
};

您还没有证明提供的代码element ,所以范围(没有双关语意)把这个所有的功能,并引用您的全局window ,或在一个命名空间(实际上另一个一次性嵌套包装功能部件)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM