javascript - 如何运行 jquery 下拉菜单打开/关闭

标签 javascript jquery css drop-down-menu

我的元素是一个带有选择(此处为国家)而不是链接的下拉菜单,它必须类似于带有某些选项的选择

当我只有一个下拉菜单时,我的下拉菜单出现问题,一切正常, 但我的元素中有 4 个,当打开/关闭下拉列表或在下拉列表中做出选择时,我会看到一些 react 。 未关闭或仅关闭一项而其他下拉菜单保持打开状态 我留下来但不满足

我的代码在这里以获取更多详细信息

$(document).ready(function(){
var $container = $('.dropdown-menu'),
    $list = $('.dropdown-menu ul'),
    listItem = $list.find('li');

$(".dropdown .title").click(function () {
    if($container.height() > 0) {
        closeMenu(this);
    } else {
        openMenu(this);
    }
});

$(".dropdown-menu li").click(function () {
    closeMenu(this);
});

function closeMenu(el) {
    $(el).closest('.dropdown').toggleClass("closed").find(".title").text($(el).text());
  $(el).next().css("height", 0);
    $list.css( "top", 0 );
}

function openMenu(el) {console.log(el);
    $(el).parent().toggleClass("closed");

    $(el).next().css({
        height: 200
    })
        .mousemove(function(e) {
        var heightDiff = $list.height() / $container.height(),
            offset = $container.offset(),
            relativeY = (e.pageY - offset.top),
            top = relativeY*heightDiff > $list.height()-$container.height() ?
            $list.height()-$container.height() : relativeY*heightDiff;

      //  $list.css("top", -top);
    });
}
});

https://jsfiddle.net/yuki95/0wo01j8y/

感谢您的帮助。

最佳答案

我相信不一致的行为是由这一行引起的

if($container.height() > 0) {

尝试检查关闭

if($(this).closest('.dropdown').hasClass("closed")) {

Demo

更新

为了关闭其他下拉菜单,请更改此

$(el).next().css("height", 0);

到此

$(el).closest('.dropdown').find('.title').next().css("height", 0);

并向 openMenu 函数添加代码,为所有其他关闭的菜单调用 closeMenu

$('.dropdown:not(.closed) .title').not(el).each(function(){
    closeMenu(this);
});

https://jsfiddle.net/e81Lemmg/

关于javascript - 如何运行 jquery 下拉菜单打开/关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31975783/

相关文章:

javascript - 在语义 ui 中滚动到菜单

javascript - 一旦文本区域变得可见,就转换它的值

javascript - 对 redux 存储更改使用react的正确模式

javascript - 为什么我的代码无法在 jquery 中正确计算计数?

css - 网站在平板电脑和手机上未正确对齐

javascript - 关于 JavaScript for() 循环巫术

javascript - 隐藏所有后代表行

php - 所选菜单项的浮点线颜色

css - Cordova - jQuery Mobile - 不需要的 CSS

css - flex 容器中的文本不会在 IE11 中换行