HTML 结构
我使用了JS添加,需要提取出来也比较方便,需要美化的自行添加style
CSS 代码
/*返回顶部*/ .GoTop { width: 50px; height: 45px; bottom: 55px; cursor: pointer; background: red; color: white; text-align: center; position: fixed; right: 50px; display: none; z-index: 580; }
jQuery 代码
$(function() { var globalConfig = true; //是否启用回到顶部 true启用 : false 关闭 if(!globalConfig)return false; var $GoTop = $('.GoTop'),right, $window = $(window); if(!$GoTop.length){ //如果不存在返回顶部append添加 $GoTop = $('<div class="GoTop">返回顶部</div>'); $("body").append($GoTop); } if($window.width() < 1280){ //浮动右边right距离 right = 10; } else{ right = Math.abs(($window.width() - 1200) / 2 - $GoTop.width()); //1200 定义主体宽度 $GoTop.css("right", right); } $GoTop.bind("click.GoTop", function (){ //当点击标签的时候,使用animate在500毫秒的时间内,滚到顶部 $('body,html').animate({scrollTop: 0}, "500"); }); $window.bind("scroll.GoTop", function (){ //只要窗口滚动,就触发下面代码 $(this).scrollTop()>100?$GoTop.fadeIn():$GoTop.fadeOut(); //判断滚动后高度超过100px,就显示 }); });
$(function() {
var globalConfig = true; //是否启用回到顶部 true启用 : false 关闭 if(!globalConfig)return false;
var $GoTop = $('.GoTop'),right,
$window = $(window);
if(!$GoTop.length){ //如果不存在返回顶部append添加
$GoTop = $('
');
$("body").append($GoTop); }
if($window.width() < 1280){ //浮动右边right距离 right = 10; } else{ right = Math.abs(($window.width() - 1200) / 2 - $GoTop.width()); //1200 定义主体宽度 $GoTop.css("right", right); } $GoTop.bind("click.GoTop", function (){ //当点击标签的时候,使用animate在500毫秒的时间内,滚到顶部 $('body,html').animate({scrollTop: 0}, "500"); }); $window.bind("scroll.GoTop", function (){ //只要窗口滚动,就触发下面代码 $(this).scrollTop()>100?$GoTop.fadeIn():$GoTop.fadeOut(); //判断滚动后高度超过100px,就显示
});
});
About the author