2016-12-22 116 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