JavaScript触发方法
除了使用自定义属性触发模态弹出框之外,还可以通过JavaScript方法来触发模态弹出窗。通过给一个元素一个事件,来触发。比如说给一个按钮一个单击事件,然后触发模态弹出窗。如下面的一个简单示例:
<!-- 触发模态弹出窗元素 --> <button class="btn btn-primary" type="button">点击我</button> <!-- 模态弹出窗内容 --> <div class="modal" id="mymodal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button> <h4 class="modal-title">模态弹出窗标题</h4> </div> <div class="modal-body"> <p>模态弹出窗主体内容</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button> <button type="button" class="btn btn-primary">保存</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal -->
JavaScript触发的弹出窗代码:
$(function(){ $(".btn").click(function(){ $("#mymodal").modal(); }); });
运行效果如下:
我来试试:使用JavaScript方法触发窗口框弹出。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>模态弹出窗的使用(三)</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> </head> <body> <!--下面是代码任务部分---> <button class="btn btn-primary" type="button">点击我</button> <div class="modal" id="themodal" tabindex="-1"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button> <h4 class="modal-title">模态弹出窗标题</h4> </div> <div class="modal-body"> <p>模态弹出窗主体内容</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button> <button type="button" class="btn btn-primary">保存</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> </body> </html>