您的位置:首页 > 其它

如何制作网页中回到顶部的悬浮按钮

2017-08-19 17:21 357 查看
html代码如下:
<div class="top">
<span title="Top" id="topArrow"></span>
</div>css:(添加一定的美化效果)
.top{
width: 50px;
height: 100px;
background-color: rgba(0,0,255,0.5);
border-radius: 10px;
position: fixed;
right: 100px;
bottom: 40%;
}
.top #topArrow{
width: 30px;
height: 30px;
border-top: 2px solid #fff;//利用border和rotate绘制向上的箭头
border-left: 2px solid #fff;
display: inline-block;
transform: translate(9px,35px) rotate(45deg);
cursor: pointer;
z-index: 1000;//避免被其他div遮盖
}
.top #topArrow:hover{
border-width: 4px;
}
js:
1)jQuery
$("#topArrow").click(function(){
$(document).scrollTop(0);
})
2)DOM
var topArrow=document.getElementById('topArrow');
topArrow.onclick=function(){
document.scrollTop = document.body.scrollTop =0;
}也可以通过scrollTop将页面移动到固定元素的位置,实现如下:
<img id="img1" src="public/images/bg.jpg">
<img id="img2" src="public/images/bg2.jpg">
<img id="img3" src="public/images/bg.jpg">

<div class="top">
<span title="Top" id="topArrow"></span>
</div>js代码:
var topArrow=document.getElementById('topArrow');
var img2=document.getElementById('img2');
topArrow.onclick=function(){
/*document.scrollTop = document.body.scrollTop =0;*/
var h=img2.offsetTop;
document.body.scrollTop=h;
}这里,同样点击箭头可以将页面跳转到第二张图片的位置,但是实际应用中一般将h设置小一点,如h-200,从而让跳转效果更明显。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: