我尝试编写我的第一个插件。这是一个简单的 jQuery 插件,可以根据屏幕宽度对 DOM 进行重新排序。如果插件在单个选择器上使用,$("#box3").domorder();
它会按预期工作。
但是,如果使用多个选择器来调用该函数,或者该函数被多次调用,则该函数只能在第一个选择器上工作一次。
我each(function(){})
对每个选择器进行了迭代,但我显然遗漏了一些东西。
(function($) {
"use strict";
$.fn.domorder = function(options) {
var settings = {
breakpoint : 960,
targetContainer : $(this).parent(),
targetPosition : "start"
};
if (options) {
$.extend(settings, options);
}
return this.each(function(i, el) {
/* remember selector's original order position */
var originalLocation = {};
if ($(el).prev().length) {
/* not originally first child */
originalLocation.prev = $(el).prev()[0];
} else {
/* originally a first child */
originalLocation.parent = $(el).parent()[0];
}
var initiatedomorder = function() {
var winW = $(window).width();
if (winW < settings.breakpoint && !$("body").hasClass("domorder-reordered")) {
/* dom the order of the item */
if (settings.targetPosition === "start") {
$(el).prependTo(settings.targetContainer[0]);
} else {
$(el).appendTo(settings.targetContainer[0]);
}
$("body").addClass("domorder-reordered");
} else if (winW >= settings.breakpoint && $("body").hasClass("domorder-reordered")) {
/* return the reordered item back into the orignal flow */
if (originalLocation.parent) {
/* element was a first child */
$(originalLocation.parent).prepend(el);
} else {
/* element was not a first child */
/* add a line break to preserve inline-block spacing */
$(originalLocation.prev).after(el).after("\n");
}
$("body").removeClass("domorder-reordered");
}
};
initiatedomorder();
$(window).resize(function() {
initiatedomorder();
});
});
};
}(jQuery));