簡體   English   中英

使用 URL 和哈希切換 Bootstrap 模式

[英]Toggle Bootstrap modal with URL and hash

我想使用帶有哈希值的 URL 來調用特定的 Bootstrap 模式。 換句話說,用戶在 page1 上並單擊 page2#hash 的鏈接,並且在 page2 加載時加載 #hash 模式。 根據我在其他問答中讀到的內容,我嘗試了很多變體,但沒有任何效果。 我對 JS 完全沒有經驗,所以我很感激一些幫助!

這是我所擁有的:

第 1 頁上的鏈接: <a href="/page2#myModal>

第 2 頁上的 HTML:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
  ...
</div>


第 2 頁上的 Javascript:

<script>
  if(window.location.hash) {
    var hash = window.location.hash;
    $("'" + hash + "'").modal('toggle');
  }
</script>


順便說一句, <a href="#" data-toggle="modal" data-target="#myModal">可以很好地在用戶實際位於第 2 頁時調用模態。

您正在向選擇器添加單引號,選擇器不使用引號:

$("'" + hash + "'").modal('toggle');

應該

$(hash).modal('toggle');

此外,您可能不會等待 dom 准備好使用。 如果您在頁面底部或至少在您的模態 html 所在的下方沒有該腳本,則無法找到該腳本,因為它尚未創建。

<script>
  //shortcut for $(document).ready
  $(function(){
      if(window.location.hash) {
          var hash = window.location.hash;
          $(hash).modal('toggle');
      }
  });
</script>

 $(document).ready(function () { $(window.location.hash).modal('show'); $('a.open-modal-hash').click(function () { window.location.hash = $(this).attr('href'); }); $(".modal").on("hidden.bs.modal", function () { // any time a modal is hidden var urlReplace = window.location.toString().split('#', 1)[0]; history.pushState(null, null, urlReplace); // push url without the hash as new history item }); });
 /* Modal Full Screen */ .modal-full-screen { padding: 0 !important; } .modal-full-screen .modal-dialog { width: 100%; max-width: none; height: 100%; margin: 0; } .modal-full-screen .modal-content { height: 100%; border: 0; border-radius: 0; } .modal-full-screen .modal-body { overflow-y: auto; }
 <a href="#modal-hash" class="open-modal-hash" data-toggle="modal">Open Modal</a> <div class="modal fade modal-full-screen" id="modal-hash"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h6>Title</h6> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> </div> <div class="modal-footer"> </div> </div> </div> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM