如何在Bootstrap 3选项卡上应用悬停?

时间:2018-06-04 16:32:56

标签: javascript jquery twitter-bootstrap-3

如何在此代码中添加功能,以便在鼠标从.tab-pane移出.tab时将.tab-pane保留在页面上?并且只有当鼠标从.tab-pane

悬停时才关闭它

$(".presentation").hover(function(){
  var target = $(this).data("target");
     $(target).addClass('in active');
    }, function(){
		 var target = $(this).data("target");
    $(target).removeClass('in active');
});
.tab-pane{
 background:#eee;
  height:120px;
  Padding:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
<div>

  <!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist">
    <li role="presentation"><a class="presentation" data-target="#home">Home</a></li>
    <li role="presentation"><a class="presentation" data-target="#profile" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li>
    <li role="presentation"><a class="presentation" data-target="#messages" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li>
    <li role="presentation"><a class="presentation" data-target="#settings" aria-controls="settings" role="tab" data-toggle="tab">Settings</a></li>
  </ul>

  <!-- Tab panes -->
  <div class="tab-content">
    <div role="tabpanel" class="tab-pane fade" id="home">Home</div>
    <div role="tabpanel" class="tab-pane fade" id="profile">profile</div>
    <div role="tabpanel" class="tab-pane fade" id="messages">messages</div>
    <div role="tabpanel" class="tab-pane fade" id="settings">settings</div>
  </div>

</div>
  </div>

1 个答案:

答案 0 :(得分:2)

You can use relatedTarget property of jQuery eventObject passed to the second handler of hover event:

$(".presentation").hover(
  function() {
    var target = $(this).data("target");
    $(target).addClass('in active');
  },
  function(event) {
    var target = $(this).data("target");
    var targetId = target.replace('#', '');       
    var relatedTarget = $(event.relatedTarget);

    if (relatedTarget.attr('id') === targetId) {
      return;
    }

    $(target).removeClass('in active');
  }
);

But you also need to bind mouseleave event handler on .tab-pane elements in order to properly hide them.

$('.tab-pane').on('mouseleave', function() {
  $(this).removeClass('in active');
})