在Bootstrap模态

时间:2017-12-14 12:58:08

标签: javascript jquery css twitter-bootstrap

我试图在Bootstrap模式上方显示警告div。 div应该相对于模态水平居中。

以下代码(或fiddle)就是我所做的。我的问题是shortMessage文本被包装不需要。我该如何解决?



$(document).ready(function() {
    $("#myModal").modal("show");
    $("#myButton").click(function(){
    	var shortMessage = "Lorem ipsum dolor sit amet";
        var LongMessage = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. \
                           Nullam iaculis consequat risus sit amet feugiat. \
                           Sed nec arcu quis tellus pretium malesuada id fringilla mi.";
        DisplayFadingAlert(shortMessage);
        setTimeout(function(){
      	  DisplayFadingAlert(LongMessage);
        }, 2000);
    });
});

function DisplayFadingAlert(message)
{
    $fadingAlert = $("<div />", {
        "class": "alert alert-success fading-message",
        "text": message,
    });
    $fadingAlert.appendTo($("body"));

    var MARGIN = 5;
    var modalWidth = $(".modal-content").width();
    var fadingAlertMaxWidth = parseInt(modalWidth - (MARGIN * 2));
    var fadingAlertWidth = $fadingAlert.width();
    
    if (fadingAlertWidth >= fadingAlertMaxWidth) 
      fadingAlertWidth = fadingAlertMaxWidth; 
    var modalLeft = $(".modal-content").offset().left;
    var fadingAlertLeft = modalLeft + ((modalWidth - fadingAlertWidth) / 2);

    $fadingAlert.css({
        "left": fadingAlertLeft,
        "width": fadingAlertWidth,
        "max-width": fadingAlertMaxWidth
    });

    $fadingAlert.fadeIn(300).delay(1500).fadeOut(600);;
}
&#13;
.fading-message {
  position: fixed;
  top: 0%;
  z-index: 9999;
  display: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>

<div class="modal fade" id="myModal" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        I'm a modal body
      </div>
      <div class="modal-footer">
        <button id="myButton" type="button" class="btn btn-primary">
          Display Alert
        </button>
      </div>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

这是一个演示:JS Fiddle

修复:

fadingAlertWidth没有包含导致文本换行的外部填充和边框。

相关代码:

var fadingAlertWidth = $fadingAlert.width()+32; // padding of 15px on the left and right and border of 1px each

正如评论中所述,只需设置max-widthwidth:auto

此外,fadingAlert消息被附加到正文永远不会被删除。我在DisplayFadingAlert函数中添加了以下行来解决此问题:

$('body div.alert.fading-message').remove();

希望这会有所帮助。 :)