【问题标题】:How to trigger something within a resize event with a jQuery plugin如何使用 jQuery 插件在调整大小事件中触发某些内容
【发布时间】:2015-06-10 13:10:21
【问题描述】:

我正在尝试通过制作一个很小的基本插件来进一步学习 jQuery .

仍然有一些元素,例如 CSS,对我来说还不起作用。但是我目前不知道的一件事是如何传入事件侦听器以在我的插件中调整大小?

到目前为止我的插件:

$.fn.windowSize = function( options ) {
    // outline settings
    var settings = $.extend({
        color: "#000000",
        backgroundColor: "yellow",
        position: "fixed",
        top: 0,
        left: 0
    }, options );

    // screen sizing vars
    var the_width = $(window).width();
    var the_height = $(window).height();  

    // measure html
    var measure = '<div id="measurements">' +
        '<span>Width:</span><span id="width">Risize to find out</span>' +
        '<span>Height:</span><span id="height">Risize to find out</span>' +
        '</div>';

    var measure_display = $("#measurements");

    // inject the measure elem to this
    this.prepend(measure);

    // use the default css
    return measure_display.css({
        color: settings.color,
        backgroundColor: settings.backgroundColor,
        position: settings.position,
        top: settings.top,
        left: settings.left
    });

    // sets the html to display widths
    $(window).resize(function() {
        $('#width').text(the_width);
        $('#height').text(the_height);
    });
};

Live, partially working example.

*更新

基本上,我的插件的一部分在窗口调整大小时触发了一些值,而不是用户需要在我的插件之外编写它,我希望在插件中这样做,所以我想知道这是否可能。

【问题讨论】:

  • 你的意思是每次re size时调用一个函数吗?
  • 是的,没错@lugreen
  • $( window ).resize(function() { someFunction(); }) // 调整大小时重新加载。
  • 但是有没有办法将它捆绑在插件本身中,这样用户就不需要这样做了?或者你的意思是这可以放在插件中?
  • 我不是 100% 确定我理解你,但你可以把它放在插件的底部,在任何调整大小的事件上,它都会调用你放置的任何函数/函数在。

标签: jquery


【解决方案1】:

您需要将函数作为参数传递给您的options 对象,如下所示:

$(window).resize(settings.resizeHandler);

然后你这样使用它:

$('body').windowSize({
    resizeHandler: function () {
        console.log("window resize");
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    • 1970-01-01
    • 2021-08-04
    • 2010-12-21
    相关资源
    最近更新 更多