作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 JavaScript 和 jQuery 的初学者。我的 css 和 JavaScript 代码位于 html 文件外部。这个问题已经有了答案,我尝试了所有代码,但滚动不起作用。我不知道我错过了什么。 jQuery 已安装(甚至 CDN)。嗯,这段代码在代码片段中工作,所以可能是 javaScript 或 JQuery 出了问题。我仍然不知道我的错误是什么。请帮忙。
$("#btn1").click(function() {
$('html,body').animate({
scrollTop: $("#fir").offset().top},
'slow');
});
$("#btn2").click(function() {
$('html,body').animate({
scrollTop: $("#sec").offset().top},
'slow');
});
.button1{ position:absolute; top:130px; left:150px; font-size: 10px; cursor:pointer; color:#000000;}
.main{ width: 100%; height:500px; background:black; }
.first{ width: 100%; height: 1000px; background: green; }
.second{ width: 100%; height: 1000px; background: blue; }
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<script src="http://code.jquery.com/jquery-2.2.1.min.js"></script> <!-- JQuery CDN -->
<script>window.jQuery || document.write('<script src="JQuery.js"><\/script>');</script> <!-- JQuery library -->
<script src="js/script.js" type="text/javascript"></script> <!-- my javascript -->
<div class="main">
<button id="btn1" type="button" class="button1">Sign Up</button>
<button id="btn2" type="button" class="button1" style=left:250px>Sign In</button></div>
<div id="fir" class="first"></div>
<div id="sec" class="second"></div>
</body>
</html>
最佳答案
我已将(为了简化测试)所有元素合并到单个 .html 文件中,并进行了一些修改,它对我有用:
script
标记移动到文档末尾document.ready()
逻辑<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<style type="text/css">
.button1{ position:absolute; top:130px; left:150px; font-size: 10px; cursor:pointer; color:#000000;}
.main{ width: 100%; height:500px; background:black; }
.first{ width: 100%; height: 1000px; background: green; }
.second{ width: 100%; height: 1000px; background: blue; }
</style>
<div class="main">
<button id="btn1" type="button" class="button1">Sign Up</button>
<button id="btn2" type="button" class="button1" style=left:250px>Sign In</button></div>
<div id="fir" class="first"></div>
<div id="sec" class="second"></div>
<script src="http://code.jquery.com/jquery-2.2.1.min.js"></script> <!-- JQuery CDN -->
<script type="text/javascript">
$( document ).ready(function() {
$("#btn1").click(function() {
$('html,body').animate({
scrollTop: $("#fir").offset().top},
'slow');
});
$("#btn2").click(function() {
$('html,body').animate({
scrollTop: $("#sec").offset().top},
'slow');
});
});
</script>
</body>
</html>
关于javascript - 按钮点击平滑滚动 : Not working for me but works great in the Code Snippet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36042436/
我是一名优秀的程序员,十分优秀!