$(document).ready(function () { var dropdown = ''; var menu = ''; var tag = ''; var dropdownHeight = 0; var menuHeight = 0; $('.dropdown-menu').mCustomScrollbar({ advanced: { updateOnContentResize: true } }); $('.dropdown-toggle').click(function () { // 先收起其他展开的,在展开 $('.dropdown.open').not($(this).parents('.dropdown')).each(function() { $(this).removeClass('open').find('.dropdown-menu').slideUp(); }); // 展开点击的 dropdown = $(this).parents('.dropdown'); menu = dropdown.find('.dropdown-menu'); tag = dropdown.find('.tag'); if (menu.is(":hidden")) { // 因此其他 menu.css({ height: 'auto' }) menu.show(); dropdownHeight = dropdown.outerHeight(); menuHeight = menu.outerHeight(); menu.hide(); } if (!menu.is(":hidden")) { dropdown.removeClass('open'); menu.slideUp(); } else { menu.slideDown(); dropdown.addClass('open'); } updateDropdownPosition(); }); $(document).click(function (e) { if (!$(e.target).closest('.dropdown').length && dropdown) { dropdown.removeClass('open'); menu.slideUp(); } }); $('.dropdown-menu li').click(function () { var selectedText = $(this).text(); $(this).parents('.dropdown').find('.input-value').val(selectedText); // 设置标签 tag.text(selectedText); dropdown.removeClass('open'); menu.slideUp(); }); $(window).resize(function () { if (dropdown) { updateDropdownPosition(); } }); $(window).scroll(function () { if (dropdown) { updateDropdownPosition(); } }); function updateDropdownPosition() { var offset = dropdown.offset(); var top = offset.top + dropdownHeight; var windowHeight = $(window).height(); var scrollTop = $(window).scrollTop(); if (top + menuHeight > windowHeight + scrollTop) { menu.css({ top: 'auto', bottom: dropdownHeight + 'px' }); } else { menu.css({ top: dropdownHeight + 'px', bottom: 'auto' }); } } });