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

问题描述 投票:0回答:6

我正在使用 Bootstrap 3.0,并且有一个打开的模态窗口,底部有两个“按钮”,一个显示“联系我们”,另一个显示“关闭”。

当有人单击“联系我们”按钮时,我希望关闭模态窗口,并将用户自动带到同一页面上的特定锚点。

以下内容不起作用。它确实将页面滚动到所需的锚点,但用户看不到这一点,因为它没有关闭模式窗口...

<a class="btn btn-info" data-dismiss="modal" href="#section-contact">Contact Us</a>
javascript jquery twitter-bootstrap modal-dialog
6个回答
3
投票

您是否尝试过或考虑过在关闭按钮上使用 jquery onclick 函数?

也许您可以强制模式手动关闭(请参阅文档

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

并使用导航到锚点(参见答案

$(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);
});

3
投票

我也遇到过同样的问题,但Lan提供的答案对我不起作用。

最后,我通过使用

onClick
来关闭模态类
.modal
而不是使用我想要关闭的特定模态
#myModal
的 id 来解决这个问题。这是有效的,因为您的网络中一次只能打开一个模式:

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

2
投票

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>

在此示例中,哈希将是#products,但它将更新为您可能拥有的任何其他锚点


0
投票

我正在使用另一种解决方案来解决这个问题。当我有一个带有“部分”概述的模式时,我遇到了同样的问题,并且我想在同一页面上跳出此模式到特定部分。我只需在链接中传递部分 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
}

0
投票

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

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

0
投票

这是在普通 JavaScript 中执行此操作的最简单方法,而不会在模式仍在关闭时触发由页面滚动引起的奇怪的竞争条件:

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

记得将

#yourModal
#yourAnchor
替换为你自己的。

© www.soinside.com 2019 - 2024. All rights reserved.