向上滚动到浏览器顶部固定住,向下滚动出浏览器顶部回复原状

本文介绍了一个使用JavaScript实现的方案,当页面滚动到浏览器顶部时,指定元素会固定显示,不会随页面滚动。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[color=blue]js代码:[/color]

//当滚动到浏览器顶部时 浮动固定 不随网页滚动
var title_fix=function(){
//元素距离网页头部的距离
this.e_top=0;
this.posi=function()
{
//被卷入的的网页高度
var sTop=document.documentElement.scrollTop+document.body.scrollTop;
//计算出元素距离浏览器顶端的距离
if((this.e_top-sTop)<=0)
{
document.getElementById("title_id").setAttribute("class","css_title_fixed");
}else{
document.getElementById("title_id").setAttribute("class","css_title");
}
};
}


[color=blue]html代码:[/color]


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN" dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>测试</title>
<script type="text/javascript" src="scrolltotop.js"></script>
<style>
.css_title{
height:50px;width:100%;background-color: #ED0BE2;line-height: 50px;
}
.css_title_fixed{
height: 50px;width: 100%;background-color: #ED0BE2;line-height: 50px;position: fixed;left: 0px;top: 0px;
}
</style>
</head>
<body id="top">
<div style="height:300px;width:100%;background-color: #eee;"></div>
<div style="height:300px;width:100%;background-color:#dddddd;"></div>
<div style="height:300px;width:100%;background-color:#ffffff;"></div>
<div style="height:300px;width:100%;background-color:#00ff00;"></div>
<div class="css_title" id="title_id">
菜单
</div>
<div style="height:300px;width:100%;background-color:#ffddee;"></div>
<div style="height:300px;width:100%;background-color:#eeff00;"></div>
<div style="height:300px;width:100%;background-color:#ddeeff;"></div>
<a id="totop_btn" href="javascript:;" onclick="scrolltotop.scrolltop()" target="_self" class="totop"
style="position:fixed;right:10px; bottom:10px;width:100px;height50px;line-height:50px;text-align:center;background-color: #ff0000;display:none;">
返回顶部
</a>
</body>
<script>
var a = new title_fix();
a.e_top=document.getElementById("title_id").offsetTop;
window.onscroll = function(){
scrolltotop.scrollevent();
a.posi();
}
</script>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值