.animate()查询不起作用
问题描述:
我想在我的静态HTML网站中实现一个“回滚到顶部”按钮,就像我之前做过一百万次那样。所以我加了这段代码: (第一部分是关于制造一定时间后会出现按钮,不用担心).animate()查询不起作用
$(document).ready(function() {
$(window).scroll(function() {
var scroll = $(document).scrollTop();
var wheight = $(window).height();
var hheight = wheight/2;
if(scroll >= hheight) {
$('#scroller').css({'opacity': '1'});
} else if (scroll <= hheight) {
$('#scroller').css({'opacity': '0'});
}
});
$('#scroller').click(function() {
alert("click works!");
$('html, body').animate({ scrollTop: 0 }, 500);
});
});
的出现和按钮的作品消失,它也提醒“,点击作品“如果我点击按钮。但滚动不起作用。我搞不清楚了。我读的地方,你不应该在你的CSS使用height: 100%
和使用
height: auto;
min-height: 100%;
代替。这不会改变一件事情。我也尝试使用document
作为滚动元素。
如果有人能帮助我,我很高兴!
答
看来你的代码工作:
$(document).ready(function() {
$(window).scroll(function() {
var scroll = $(document).scrollTop();
var wheight = $(window).height();
var hheight = wheight/2;
if(scroll >= hheight) {
$('#scroller').css({'opacity': '1'});
} else if (scroll <= hheight) {
$('#scroller').css({'opacity': '0'});
}
});
$('.scroll').click(function() {
$('html, body').animate({ scrollTop: 0 }, 500);
});
});
* {
box-sizing: border-box;
}
html, body {
margin: 0;
}
body {
background: linear-gradient(to top, red, blue);
height: 2000px;
border: 10px solid goldenrod;
position: relative;
}
.scroll {
font-size: 2em;
position: absolute;
bottom: 0;
display: block;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="scroll">scroll</button>
答
我得到它的工作! 我使用了jQuery的超薄版本。 只要我切换到正常生产版本一切正常。
你能提供html吗?如果你有'html,body,#wrapper {height:100%; }',你可能不得不通过'$('html,body,#wrapper')。animate({scrollTop:0},500)更改你的代码;' – Kangouroops
不幸的是, – Pixell