44

我正在开发的部分页面需要在用户单击按钮时将 $(window).resize 事件添加到 div 中,以便在使用窗口调整窗口大小和将其固定为原始大小之间切换:

function startResize() {
    $(window).resize(function() {
        $("#content").width(newWidth);
        $("#content").height(newHeight);
    });
}

我无法解决的是如何在再次单击按钮时“关闭”此事件,以便内容停止调整大小。

function endResize() {
    // Code to end $(window).resize function
    $("#content").width(originalWidth);
    $("#content").height(originalHeight);
}

对此的任何帮助将不胜感激。

4

2 回答 2

93
function endResize() {
    $(window).off("resize");
    $("#content").width(originalWidth);
    $("#content").height(originalHeight);
}

请注意,这是非常突兀的,可能会破坏其他代码。

这是更好的方法:

function resizer() {
    $("#content").width(newWidth);
    $("#content").height(newHeight);
}

function startResize() {
    $(window).resize(resizer);
}

function endResize() {
    $(window).off("resize", resizer);
}
于 2012-11-07T11:05:59.753 回答
60
function startResize() {
   $(window).on("resize.mymethod",(function() {
     $("#content").width(newWidth);
     $("#content").height(newHeight);
   }));
}

function endResize() {
   $(window).off("resize.mymethod");
}

在查询方法上使用命名空间将允许只为您的方法关闭调整大小事件。

于 2013-12-20T00:29:44.760 回答