繁体   English   中英

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

[英]How do I close a Modal window and automatically navigate to Anchor using the same link?

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

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

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

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

您是否尝试或考虑过关闭按钮上的 jquery onclick 功能?

也许你可以强制模式手动关闭(参见文档

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

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

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

结果将是:

HTML :

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

查询

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

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

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

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

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,但它会更新为您可能拥有的任何其他锚点

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM