JavaScript滚动到div元素的ID

13

我在谷歌上搜索了解决我的问题的方法,但是我不明白为什么我写的代码对别人都有效,但对我无效。

我写的是这个:

<head>
    <meta charset="utf-8" />
    <title></title>
    <script type="text/javascript">
        function scrollTo() {
            $('html, body').animate({ scrollTop: $('#div_id').offset().top }, 'slow');
            return false;
        }
    </script>
    <style type="text/css">
        .uno {
            height: 1000px;
            background: #808080;
        }
        .due {
            margin-top: 300px;
            height: 500px;
            background: #ff00ff;
        }
    </style>
</head>
<body>
    <div class="uno" onclick="scrollTo()"> 
        Clicca
    </div>
    <div class="due" id="div_id"></div>
</body>

4
你是否已经包含了 jQuery 库? - Rohit Batham
1
在发布问题到 Stack Overflow 上之前,为什么不先检查控制台呢? :) - Yury Tarabanko
3个回答

21
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script type="text/javascript">
        function scrollTo() {
            $('html, body').animate({ scrollTop: $('#div_id').offset().top }, 'slow');
            return false;
        }
    </script>
    <style type="text/css">
        .uno {
            height: 1000px;
            background: #808080;
        }
        .due {
            margin-top: 300px;
            height: 500px;
            background: #ff00ff;
        }
    </style>
</head>
    <body>
        <div class="uno" onclick="scrollTo()"> 
        Clicca
        </div>
        <div class="due" id="div_id"></div>
    </body>
</html>

试试这个:


1
请尝试在上述代码中包含jQuery库后再运行,看看是否有效。 - Rohit Batham
如果推荐的解决方案解决了您的问题,请将其接受为答案。这也可以帮助其他人。 - Pugazh
@SyncCircles 谢谢同步。 - Rohit Batham
当然可以,但我需要等待几分钟。这就是为什么我还在这里的原因。 - ProtoTyPus
这不是Javascript,你能否也更新一下如何仅使用Javascript来完成这个任务?我正在开发Chrome扩展程序。 - Hemant Kumar
显示剩余2条评论

4
将您的脚本更改为:

$('.uno').on('click', function(){
    $('html, body').animate({scrollTop: $("#div_id").offset().top}, 'slow');
});

并从第一个div中删除 onclick

演示在这个 jsFiddle中。


3

请查看我的jsfiddle:

你需要在代码中添加jquery,并且这是我推荐的方式:

JSFIDDLE

在这个jsfiddle中,如果你点击每个div,你会滚动到另一个div。 DEMO

Javascript

$("#firstDiv").click(function(){
        $('html, body').animate({ scrollTop: $('#div_id').offset().top }, 'slow');

 })

HTML

<div class="uno" id="firstDiv"> 
    Clicca
</div>
<div class="due" id="div_id"></div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接