平滑滚动 JavaScript 影响模态功能

Smooth scrolling JavaScript affecting Modal functionality

本文关键字:模态 功能 影响 JavaScript 滚动 平滑      更新时间:2023-09-26

我正在使用以下JavaScript为我的页面执行平滑滚动。

$(function(){
    $('a[href*="#"]:not([href="#"])').click(function() {
        if (location.pathname.replace(/^'//,'') == this.pathname.replace(/^'//,'') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
            if (target.length) {
                $('html, body').animate({
                    scrollTop: target.offset().top
                }, 1000);
                return false;
            }
        }
    });
});

这工作正常,但它对我的模态有不良影响,因为它会阻止模态打开。我的滚动版:

<a href="#location" class="btn btn-circle">
    <i class="fa fa-5x fa-angle-double-down animated"></i>
</a>

对于我的模态:

<div class="panel-group" id="accordion">
    <div class="panel panel-default">
        <div class="panel-heading">
            <h4 class="panel-title">
                <a data-toggle="collapse" data-parent="#accordion" class="collapsed"  href="#1">
                    <span>Press for magic</span>
                </a>
            </h4>
        </div>
        <div class="collapse panel-collapse" id="1">
            <div class="panel-body">
                <p>Some magic here...</p>
            </div>
        </div>
    </div>
</div>

有没有办法修改 JavaScript 以仅对滚动产生影响并保留模态?

只需将点击函数中的a[href*="#"]:not([href="#"])替换为类名,然后将该类名放在<a>标签中,如下所示:

$(function(){
    $('.hashscroll').click(function() {
        if (location.pathname.replace(/^'//,'') == this.pathname.replace(/^'//,'') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
            if (target.length) {
                $('html, body').animate({
                    scrollTop: target.offset().top
                }, 1000);
                return false;
            }
        }
    });
});

<a class="hashscroll" href="#location" class="btn btn-circle">
    <i class="fa fa-5x fa-angle-double-down animated"></i>
</a>

不要对整个页面进行动画处理。只需为要移动的内容设置动画即可。

<body>
    <div class="animateThis"></div>
    <div class="modal"></div>
</body>