【问题标题】:Using Bootstrap data-toggle="collapse" and scrollIntoView() to show and scroll to content使用 Bootstrap data-toggle="collapse" 和 scrollIntoView() 显示和滚动到内容
【发布时间】:2015-06-28 14:06:15
【问题描述】:

在我使用 Bootstrap 3 构建的网站上,有一个部分使用 collapse 类隐藏。我添加了一个按钮来切换该部分,使其可见。这一切都很好。我需要的是能够切换内容并在显示部分时滚动到该部分。

这是我的按钮代码:

<button class="btn btn-lg btn-primary" href="#benefits" data-toggle="collapse">Learn More</button>

这是我的内容:

<section id="benefits" class="text-white collapse" data-toggle="collapse">
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                Text goes here
            </div>
        </div>
    </div>
</section>

最后,在这里我尝试使用 jQuery 将事物绑定在一起(虽然我的 jQuery 技能非常有限):

$(document).ready(function() {
    $("#benefits").bind('shown', function() {
        document.getElementById('benefits').scrollIntoView();
    });
});

谁能发现我上面代码的问题,或者提出更好的解决方案?

【问题讨论】:

    标签: jquery twitter-bootstrap


    【解决方案1】:

    您应该绑定到 Bootstrap 折叠插件中的相应事件:http://getbootstrap.com/javascript/#collapse-events

    $('#benefits').on('shown.bs.collapse', function () {
      this.scrollIntoView();
    });
    
    【解决方案2】:

    如果你想要一个比 this.scrollIntoView() 更好的动画,请使用。然后你可以调整动画速度。

    $('#benefits').on('shown.bs.collapse', function () {
        $('html, body').animate({
           scrollTop: $("#benefits").offset().top
        }, 1000);
    });
    

    【讨论】:

    • 比 scrollIntoView 更优雅的用户体验
    • 好多了,谢谢!
    【解决方案3】:

    从事件中获取元素

        $(document).on('shown.bs.collapse', function(event){
            //console.log( "in! print e: " +event.type);
            event.target.scrollIntoView();
        });
    

    【讨论】:

    • 如果有人想在页面上全局应用它,而不仅仅是特定元素,那就太好了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 2021-03-12
    • 2020-07-28
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    相关资源
    最近更新 更多