Bootstrap Dropdown:重新渲染时添加类

时间:2018-01-17 14:44:48

标签: javascript jquery html css twitter-bootstrap

Bootstrap的.dropdown.show .dropdown-menu在滚动时更改其位置top / bottombottom / top,始终在视野中。

如果发生这种情况,我可以向rendered-on-top父母添加课程rendered-on-bottom / .dropdown吗?

我注意到,只要重新渲染,它就会向x-placement元素添加.dropdown-menu属性。

类似的东西:

$('.dropdown').on('render', function(ev) {

    $(this).addClass(ev.direction);

});

ev.direction.dropdown-toggle相关的位置。

Fiddle

enter image description here

2 个答案:

答案 0 :(得分:1)

您可以使用dropdown menu的{​​{1}}属性在滚动条件中添加或删除类。我已经创建了一个函数 addYourClass(),您可以在滚动点击事件

上触发

在下面的代码段中滚动时,您可以看到更改background-color效果。

Stack Snippet

$(document).on('scroll click', function() {
  addYourClass($(".dropdown"));
});
$(document).on('click','.dropdown .btn', function() {
  addYourClass($(".dropdown"));
});

function addYourClass($item) {
  if ($('.dropdown-menu.show').length) {
    if ($item.find(".dropdown-menu").attr("x-placement") == "bottom-start") {
      $item.addClass("rendered-on-bottom").removeClass("rendered-on-top");
    } else if ($item.find(".dropdown-menu").attr("x-placement") == "top-start") {
      $item.addClass("rendered-on-top").removeClass("rendered-on-bottom");
    }
  } else {
    $item.removeClass("rendered-on-top rendered-on-bottom");
  }
}
.dropdown {
  margin: 200px 150px 0;
}

body {
  height: 600px;
}

.dropdown.rendered-on-top .btn {
  background: red !important;
}

.dropdown.rendered-on-bottom .btn {
  background: blue !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.min.js" integrity="sha384-a5N7Y/aK3qNeh15eJKGWxsqtnX/wWdSZSKp+81YjTmS15nvnvxKHuzaWwXHDli+4" crossorigin="anonymous"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
<div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropdown button
  </button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
    <a class="dropdown-item" href="#">Action</a>
    <a class="dropdown-item" href="#">Another action</a>
    <a class="dropdown-item" href="#">Something else here</a>
  </div>
</div>

答案 1 :(得分:0)

$(".dropdown").on("shown.bs.dropdown",function(){
  var ele = $(this).find(".dropdown-menu");
  $(document).on("scroll",ddonchange(ele));
});
function ddonchange(ele){
    if($(ele).attr("x-placement")=='bottom-start')
        $(ele).parent().addClass("myclass");
}