我试图通过制作一个小小的基本插件来进一步学习jQuery,这个插件会注入一些HTML,将CSS应用到该元素(可以通过将选项传递到调用中来更改),最后显示屏幕宽度和高度调整大小。
还有像CSS这样的元素对我不起作用。但是,目前我还不知道的一件事是如何通过一个事件监听器传递我的插件中的resize?
我的插件到目前为止:
$.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
*更新
基本上我的插件中有一部分是在窗口大小调整时触发了一些值,而不是用户需要在插件外写这个我希望在插件中这样,所以我想知道这是否可行。
答案 0 :(得分:0)
您需要将函数作为参数传递给options
对象,如下所示:
$(window).resize(settings.resizeHandler);
然后你就这样使用它:
$('body').windowSize({
resizeHandler: function () {
console.log("window resize");
}
});