jQuery中ScrollTop的问题(主要在Chrome中)

时间:2017-03-05 13:05:08

标签: javascript jquery scrolltop

所以我在网站上使用scrollTop时遇到了问题。我已经制作了一些测试代码,并且我已经设法让它在Firefox中运行,但它仍然拒绝在Chrome中工作......我真的看不出代码有什么问题。我添加了一个console.log()来显示偏移量的值,这很好用,但Chrome浏览器不会滚动到id =“search”的div。任何人都能看到我做错的事吗?

<a href="#" id="test-btn" class="darhoudou-button">Test</a>

<div class="test-box">test1</div>
<div class="test-box">test2</div>
<div class="test-box">test3</div>
<div class="test-box">test4</div>
<div class="test-box" id="search">test5</div>
<div class="test-box">test6</div>

<script>
     $(document).ready(function(){

        $('#test-btn').on('click', function(){

            $('html, body').animate({
                scrollTop: $('#search').offset().top
            }, 200);

        });

        console.log($('#search').offset().top);         
    });
</script>

2 个答案:

答案 0 :(得分:0)

我测试了你的代码,没有问题。

如果您的浏览器高度为500px且页面为600px,则只能滚动100px。如果页面高度小于500px,那么就没有Scroll。

请将此<div class="test-box">test6</div>更改为:

<div class="test-box" style="height:1000px;">test6</div>

查看结果,或者您可以使用chrome测试此代码段:

 <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>


<a href="#" id="test-btn" class="darhoudou-button">Test</a>

<div class="test-box">test1</div>
<div class="test-box">test2</div>
<div class="test-box">test3</div>
<div class="test-box">test4</div>
<div class="test-box" id="search">test5</div>
<div class="test-box" style="height:1000px;">test6</div>

<script>
     $(document).ready(function(){

        $('#test-btn').on('click', function(){

            $('html, body').animate({
                scrollTop: $('#search').offset().top
            }, 200);

        });

        console.log($('#search').offset().top);         
    });
</script>

答案 1 :(得分:0)

<强>解决

原来这是我的css文件导致问题...如果其他人遇到类似的问题,我会建议逐个注释掉任何js和css文件,看看是否修复它。这可能有助于您确定导致问题的文件...

我的CSS的问题如下:

 html { 
    overflow: hidden;
    height: 100%;
}    


body {
    overflow: auto;
    height: 100%;
}