Bootstrap 如何关闭Modal窗口并使用相同的链接自动导航到锚?

lf5gs5x2  于 12个月前  发布在  Bootstrap
关注(0)|答案(6)|浏览(116)

我正在使用Bootstrap 3.0,我有一个打开的Modal窗口,底部有两个“按钮”,一个说“联系我们”,另一个说“关闭”。
当有人点击“联系我们”按钮,我希望模态窗口关闭,用户将自动采取在同一页面上的特定锚。
以下内容不起作用。它确实会将页面滚动到所需的锚点,但用户看不到这一点,因为它没有关闭模态窗口...

<a class="btn btn-info" data-dismiss="modal" href="#section-contact">Contact Us</a>
wnvonmuf

wnvonmuf1#

你有没有试过或者想过在关闭按钮上使用jquery onclick函数?
也许你可以强制模态关闭manualy与(见文档)

$('#myModal').modal('hide');

并使用导航到锚点(参见answer

$(document.body).scrollTop($('#anchorId').offset().top);

结果将是:

HTML

<a class="btn btn-info" href="#" id="contact_btn">Contact Us</a>

jquery

$('#contact_btn').click(function(){
    $('#myModal').modal('hide');
    $(document.body).scrollTop($('#anchorId').offset().top);
});
jbose2ul

jbose2ul2#

我也遇到过同样的问题,但Lan提供的答案对我不起作用。
最后,我使用onClick关闭模态类.modal,而不是使用我想要关闭的特定模态#myModal的id。这是因为你在web中一次只能打开一个模态:

<a href="#section-contact" onClick="$('.modal').modal('hide');">Contact us</a>
ercv8c1e

ercv8c1e3#

Js

// .my-anchor = the class of the trigger
$('.my-anchor').on('click', function(e) {
    e.preventDefault();

    // it will search throughout .my-anchor ancestors to find the closest .modal
    $(this).closest('.modal').modal('hide');

    var hash = this.hash;

    $('html, body').animate({ scrollTop: $(hash).offset().top }, 300);
});

HTML

// clicking this link will close the modal and scroll to wherever #products is located on the page
<a href="#products" className="my-anchor">Click Here</a>

在本例中,hash将是#products,但它将更新为您可能拥有的任何其他锚

ffx8fchx

ffx8fchx4#

我正在使用另一种解决方案来解决这个问题。我有同样的问题,而我有一个模态与“节”概述,我想跳出这个模态在同一页上的一个特定的部分。我只是在链接中传递节ID,然后通过GET选择节ID,并为节创建一个PHP头。
我的HTML链接在模态:

<a class="small text-primary stretched-link" href="1.php?section_id=123"></a>

我的PHP代码在同一页上(在头的某个地方):

if($_GET){
  $section_id = $_GET['section_id'];
  header("Location: 1.php#$section_id");
} 
if(!$_GET){
  // Nichts wurde übergeben
}
kxe2p93d

kxe2p93d5#

其他的答案都不适合我。但这段代码做到了:

<a href="#contact" onclick='$(".modal").parent().hide()'>contact form</a>
wnavrhmk

wnavrhmk6#

下面是最简单的方法,在vanilla JavaScript中,在模态仍然关闭时,不会触发页面滚动引起的奇怪的竞争条件:

document.querySelector("#yourModal").addEventListener("hidden.bs.modal", function() {
   window.location.href = window.location.href.split("#")[0] + "#yourAnchor";
});

请记住将#yourModal#yourAnchor替换为您自己的。

相关问题