前端笔试题笔记(回到顶部组件)

来源:互联网 发布:网络作家排行 编辑:程序博客网 时间:2024/04/29 15:43

前端笔试题笔记(回到顶部组件)

题目要求:当页面向下滚动距顶部一定距离(如100px)时出现,向上回滚距顶部低于同样距离时隐藏,点击返回顶部组件时页面滚动到顶部;


这题一共4个问题要解决:向下滚动距顶部一定距离(如100px)时出现、上回滚距顶部低于同样距离时隐藏、点击返回顶部组件时页面滚动到顶部、始终定位在某个位置(一般来说是右下角)
第一个和第二个问题用在window.onscrollTop中,判断document.body.scrolTop的值加以判断即可,同时设定空间的display最原始的为none,要显示的时候设定为block即可。第三个问题就是设定document.body.scrollTop=”0px”就可以了。第四个问题有两个方法,1:position为fixed,然后设定right,bottom或者left,top。2:position为absolute,然后在滚动时不断调整top属性值,向下滚动多少top值就增加多少

方法一

最简单的方法,就是使用超链接标签,设置href属性为”#”,然后在window.onscroll方法中控制标签的出现和隐藏

方法二

使用按钮,在onclick事件中设置window.onscrollTop=”0px”即可
完整代码:

<!DOCTYPE HTML><html><head>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">    <title>返回顶部</title>    <style type="text/css">    #GoTop{        position:fixed;        display:none;        right:20px;        bottom:50px;    }    #GoTopa{        display:none;        position: fixed;        bottom: 25px;        right: 20px;        height: 25px;        width:25px;        text-decoration: none;        overflow: hidden;        background-image: url(http://edu.qzonestyle.gtimg.cn/aoi/sprite/icenter.32-man150205175833.png);        background-position: -153px 0;    }    </style></head><body style="height:2000px"><input id="GoTop" type="button" onclick="GoTop()" value="返回顶部"><a id="GoTopa" href="#"></a><script>window.onload=function (){    var screenw = document.documentElement.clientWidth || document.body.clientWidth;      var screenh = document.documentElement.clientHeight || document.body.clientHeight;    var oTop=document.getElementById("GoTop");    var oTop1=document.getElementById("GoTopa");    window.onscroll=function(){        var scrolltop = document.documentElement.scrollTop || document.body.scrollTop;        if(scrolltop>100){            oTop.style.display="block";            oTop1.style.display="block";            //如果position设置为absolute,则使用这句代码使控件始终停留在页面的右下角            //oTop.style.top=screenh - oTop.offsetHeight + scrolltop-10 +"px";        }else{            oTop.style.display="none";            oTop1.style.display="none";        }    }}function GoTop(){    //下面两句代码效果一样,为了兼容起见    document.documentElement.scrollTop=0;    document.body.scrollTop=0;}</script></body></html>
1 0