jQuery实现带动画效果的返回顶部按钮与滚动处理
作者:窗边听雨时间:2026-10-22 05:35:24浏览:370
本文介绍如何使用jQuery实现带动画效果的返回顶部按钮,包含显示隐藏逻辑、CSS样式定位及点击滚动至顶部的实现。同时提供包含iframe框架时的特殊滚动处理代码,确保在不同浏览器环境下功能正常。
jQuery返回顶部按钮实现
首先定义jQuery脚本逻辑。
<script type="text/javascript">
$(function() {
var scrollDiv = document.createElement('div');
$(scrollDiv).attr('id', 'toTop').html('^ 返回顶部').appendTo('body');
$(window).scroll(function() {
if ($(this).scrollTop() != 0) {
$('#toTop').fadeIn();
} else {
$('#toTop').fadeOut();
}
});
$('#toTop').click(function() {
$('body,html').animate({ scrollTop: 0 }, 800);
})
});
</script>
接着配置CSS样式以控制按钮外观。
<style type="text/css">
#toTop
{
width: 100px;
z-index: 10;
border: 1px solid #333;
background: #121212;
text-align: center;
padding: 5px;
position: fixed;
bottom: 0px;
right: 0px;
cursor: pointer;
display: none;
color: #fff;
text-transform: lowercase;
font-size: 0.9em;
}
</style>
iframe框架下的滚动处理
针对包含iframe框架的页面,需额外处理滚动行为。
<script type="text/javascript">
<!--
$().ready(function() {
$('<div id="return_old_tips" class="btn_return_old" style="position:' + ($.browser.msie ? "absolute" : "fixed") + ';" onclick="return_old({$feedback_flag},\'{$current_url}\')">返回旧版</div>').appendTo($("body"));
if ($.browser.msie) {
$("#return_old_tips").css("top", 200);
}
if ($.browser.msie) {
top.document.body.onscroll = function() {
var f = 200 + (top.document.documentElement.scrollTop || top.document.body.scrollTop);
if (f > parseInt($("body").height(), 10)) {
f = parseInt($("body").height(), 10);
}
$("#return_old_tips").css({
top: f,
left: 0
});
}
top.document.body.onresize = top.document.body.onscroll;
} else {
$(window.parent.document).scroll(function() {
var f = 200 + (top.document.documentElement.scrollTop || top.document.body.scrollTop);
if (f > parseInt($("body").height(), 10)) {
f = parseInt($("body").height(), 10);
}
$("#return_old_tips").css({
top: f,
left: 0
});
}).resize(function() {
var f = 200 + (top.document.documentElement.scrollTop || top.document.body.scrollTop);
if (f > parseInt($("body").height(), 10)) {
f = parseInt($("body").height(), 10);
}
$("#return_old_tips").css({
top: f,
left: 0
});
});
}
});
//-->
</script>
上述内容介绍了利用jQuery实现带动画效果的返回顶部按钮及scroll滚动功能,希望能对读者有所帮助。如有任何疑问,欢迎留言,小编会及时回复。同时也感谢大家对本站的支持!
作者最新文章
anime.js 快速入门:怎么引入库并编写第一个 DOM 动画
2026-11-05 14:22:43
在线JS解密后变量名仍乱码?结合浏览器DevTools调试还原
2026-11-04 20:26:01
怎么在浏览器中运行JavaScript代码并查看输出结果
2026-11-04 09:07:33
JS 获取屏幕分辨率:window.screen.width 与 height 用法
2026-11-04 08:52:48
为什么推荐用DOMContentLoaded代替window.onload初始化JS
2026-11-04 08:42:33
