...在div旁或者框架旁边添加一个“回到顶部”的按钮,并且不会随着屏幕而...
发布网友
发布时间:2022-05-12 08:24
我来回答
共3个回答
热心网友
时间:2022-05-17 09:19
HTML:
<button id="gotoTop" class="gotoTop" type="button">To the top</button>
JS:
window.onload = function () {
document.getElementById('gotoTop').onclick = function () {
scrollTo(document.body, 0, 100);
}
}
function scrollTo(element, to, ration) {
if (ration < 0) return;
var difference = to - element.scrollTop;
var perTick = difference / ration * 10;
setTimeout(function () {
element.scrollTop = element.scrollTop + perTick;
scrollTo(element, to, ration - 10);
}, 10);
}
CSS:
.gotoTop {
position:fixed;
right:20px;
bottom:20px;
}
追问可以比较详细地解释一下代码吗?
热心网友
时间:2022-05-17 10:37
var ScrollButton = function(){
return {
init : function(){
var b=$(window).height()/2;
$(window).scroll(function(){
(window.innerWidth?window.pageYOffset:document.documentElement.scrollTop)>=b?$("#backTop").show():$("#backTop").hide();
});
$("#backTop").click(function(){
$("html, body").animate({scrollTop:"0px"},400);
});
}
};
}();
还是觉得jquery比较简单
#backTop{
_position:absolute; /* for IE6 */
_top: expression(documentElement.scrollTop + documentElement.clientHeight-this.offsetHeight); /* for IE6 */
}
/*scrollTop*/
#backTop {
cursor: pointer;
display: none;
position: fixed;
right: 57px;
bottom: 87px;
width: 40px;
height: 40px;
text-indent: -9999px;
background: url("../../images/totop.png") no-repeat;
}
<div id="backTop" title="返回顶部">回到顶部</div>
热心网友
时间:2022-05-17 12:12
为什么一定要用javascript呢?用css和<a>控制不更好吗?
.gotoTop {
position:fixed;
right:20px;
bottom:20px;
display: inline-block;
}
<a class="gotoTop" href="#">
<input type="button" value="回到顶部" />
</a>追问怎么设置相对比较缓慢地回到顶部呢
追答想缓慢的话,就只能用js来控制了。