将不同的ID添加到2个不同的Bootstrap模态背景中

时间:2015-08-07 08:19:00

标签: javascript jquery html twitter-bootstrap responsive-design

我在页面上有2个模态,每个模态都有不同的行为,如果页面大于指定的宽度,则会将一个模态转换为页面内容。为了使我能够使用jQuery来隐藏它的模态背景,但问题是该脚本还会隐藏具有正常行为的第二模态的背景。如何为每个模态背景指定不同的ID?

HTML

<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal1">
  Launch modal with modal-backdrop id 1
</button>


<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal2">
  Launch modal with modal-backdrop id 2
</button>




<!-- Modal1 modal-backdrop id 1-->
<div class="modal fade" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
<!-- Modal2 modal-backdrop id 2-->
  <div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title" id="myModalLabel">Modal title</h4>
        </div>
        <div class="modal-body">
          ...
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
 </div>

2 个答案:

答案 0 :(得分:1)

您可以使用bootstrap模态的.on('show.bs.modal'事件对您的背景进行相应更改,如下所示:

$("#myModal1,#myModal2").on('show.bs.modal', function (e) {
    var that=$(this);
    var id=that.attr('id'); //get the id of button which got clicked
    setTimeout(function(){
        $('.modal-backdrop').attr('data-id',id);
        //You can either assign it as data-* attribute or add it as class to backdrop like
        //$('.modal-backdrop').addClass(id);
    });
});

现在可以根据模态的行为使用它来进行更改。

<强> DEMO

答案 1 :(得分:0)

这将解决您的问题。

<div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" data-keyboard="false" data-backdrop="static" >