Javascript scroll to div id [closed]

匿名 (未验证) 提交于 2019-12-03 03:05:02

问题:

I've searched on google the solution to my problem, and I can't understand why the code I've written work to all, but to me don't.

I've written this:

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

回答1:

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

Try this:



回答2:

Change your script to:

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

and remove onclick from the first div.

A demo is in this jsFiddle.



回答3:

see my jsfiddle:

you should add jquery to your codes, and this is my way:

JSFIDDLE

and in this jsfiddle if you click on each div you will scroll to other 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> 



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!