select2引起的滚动问题修复
栏目:
Javascript
发布时间:2023-04-23
在一个七八年前的项目中使用了 select2 js库,select2会引起父盒子滚动条无法滚动的情况。github上有相应的 issue,但是官方并为解决。这里贴一下解决方案。
$.fn.select2.amd.require(["select2/dropdown/attachBody", "select2/utils"], (AttachBody, Utils) => {
AttachBody.prototype._attachPositioningHandler = function (decorated, container) {
var self = this;
var scrollEvent = "scroll.select2." + container.id;
var resizeEvent = "resize.select2." + container.id;
var orientationEvent = "orientationchange.select2." + container.id;
var $watchers = this.$container.parents().filter(Utils.hasScroll);
$watchers.each(function () {
$(this).data("select2-scroll-position", {
x: $(this).scrollLeft(),
y: $(this).scrollTop()
});
});
$watchers.on(scrollEvent, function (ev) {
var position = $(this).data("select2-scroll-position");
$(self).scrollTop(position.y); // patch: this => self
});
$(window).on(scrollEvent + " " + resizeEvent + " " + orientationEvent,
function (e) {
self._positionDropdown();
self._resizeDropdown();
}
);
};
});
相关 issue 地址:https://github.com/select2/select2/issues/3125
本文地址:https://www.tides.cn/p_js-select2-stop-parent-box-scroll