2016-12-22 117 views
0

我有一個模態鏈接,我想在點擊時將用戶帶到特定的位置。目前,這是第一次使用,但是在使用模式的「關閉」按鈕(而不是特定鏈接)時使用相同的模式,它也會將我發送到我的鏈接(不是預期的行爲)。Bootstrap Modal中的鏈接不能按預期工作

這是一個js小提琴,它顯示了Bootstrap模式中鏈接的奇怪行爲。 https://jsfiddle.net/x9kr2wwm/5/

我的嘗試是在這裏發現了一個非常類似的問題/答案的修改(但不是一式兩份):CSS Bootstrap close modal and go to link

HTML:

See the <a href="#getstarted" id="gotoLink" data-dismiss="modal">"Get Started"</a> section for more 

javascipt的:

jQuery(function($) { 
      $("a#gotoLink").click(function(){ 
       $('#portfolioModal1').on('hidden.bs.modal', function (e) { 
        $('html, body').animate({ 
         scrollTop: $("#getstarted").offset().top 
        }, 2000); 
       }) 
      }); 
    }); 

回答

1

<a>元素的默認行爲是將頁面重定向到其href屬性。要防止默認行爲,請使用jQuery的.preventDefault()方法。

jQuery(function($) { 
      $("a#gotoLink").click(function(event){ 
       event.preventDefault(); 

       $('#portfolioModal1').on('hidden.bs.modal', function (e) { 
        $('html, body').animate({ 
         scrollTop: $("#getstarted").offset().top 
        }, 2000); 
       }) 
      }); 
    }); 
+0

真的很感謝答案,但在包含'event.preventDefault()'之後仍然有意想不到的行爲。關閉按鈕和關閉模式仍會滾動到頁面的底部。有沒有辦法將另一個事件綁定到'.on(hidden.bs.modal ..'事件? –

+0

評論編輯 - 有沒有辦法將另一個事件,比如gotoLink的點擊事件綁定到'code' .on(hidden.bs.modal event'code' –

+0

你想要的行爲是什麼? – Micros