Javascript滚动到div id

时间:2014-06-11 08:31:21

标签: javascript jquery html css

我在google上搜索了我的问题的解决方案,我无法理解为什么我写的代码对所有人都有效,但对我来说不是。

我写过:

<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>

3 个答案:

答案 0 :(得分:17)

<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 :(得分:4)

将您的脚本更改为:

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

并从第一个div中删除onclick

演示位于this jsFiddle

答案 2 :(得分: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>