每次在顶部滚动顶部重置

scrollTop reset at the top everytime

本文关键字:顶部 滚动      更新时间:2023-09-26

我得到了以下代码:

<script type="text/javascript">
    jQuery(document).ready(function(){
    var Opened = false;
    jQuery('.expend-schedule').click(function(e){
        // On empêche l'action
        e.preventDefault();
        // Variable
        var DataType = jQuery(this).attr('data-type');
        // On va fermer toutes les tables
        jQuery('.schedule').each(function(){
            // On va fermer uniquement si ouverte
            if( jQuery(this).css('display') != 'none' && jQuery(this).attr('data-type') != DataType ){
                // On ferme
                jQuery(this).fadeOut( 500, function(){
                    // Est-ce que l'animation et l'ouverture s'est produite déjà ?
                    if(Opened === false){
                        var TableElement = jQuery('.schedule[data-type="'+DataType+'"]');
                        // On ouvre et on s'y déplace de façon automatique
                        TableElement.fadeIn(TableElement.height() * 0.47, function(){
                            jQuery('html, body').animate({  
                                scrollTop: TableElement.offset().top - 50
                            }, 'slow');
                        });
                        // On dit que c'est ouvert, afin d'empêcher l'ouverture à de multiples reprises
                        // si'il y a eu un bug
                        Opened = true;
                    }
                });
            }
        });
        // On reset
        Opened = false;
    });
</script>

这是我的页面的一个例子:

<h4 class="sep_bg"><a class="expend-schedule" data-type="week" href="#">Monday to Friday</a></h4>
<table class="schedule table table-condensed" data-type="week">
    <thead>
        <tr>
            <th style="width: 60px;">Hour</th>
            <th style="width: 710px;">Transit</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>04h</td>
            <td>04h15, 04h27, 04h39, 04h59</td>
        </tr>
    </tbody>
</table>
<h4 class="sep_bg"><a class="expend-schedule" data-type="saturday" href="#">Saturday</a></h4>
<table class="schedule table table-condensed" data-type="saturday">
    <thead>
        <tr>
            <th style="width: 60px;">Hour</th>
            <th style="width: 710px;">Transit</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>04h</td>
            <td>04h15, 04h27, 04h39, 04h59</td>
        </tr>
    </tbody>
</table>

所以我的问题是:

每次我单击类expend-schedule所在的位置时,它都应该从当前滚动位置移动到元素位置。这是有效的,除了当我单击时,它直接进入页面顶部,然后移动到元素位置。

有什么想法吗?谢谢。

我认为

它不会达到顶部,我尝试使用您提供的代码对其进行测试(缺少一些括号)。无论如何,我认为淡出会导致事物移动到顶部然后下降的感觉,因为您的 scrollTop 在动画完成功能中。如果你去掉淡入淡出,那么它就可以正常工作,尽管对我来说它只在下一次点击没有做任何事情时起作用。

因此,在没有褪色的情况下测试它,看看它是否仍在做你认为它正在做的事情。

浏览器似乎首先尊重<a href="#">链接,将其带到页面顶部,然后执行动画。

我会将其更改为<a href="javascript:void(0);">Text</a>以解决此问题。