可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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>