纯jQuery实现页面置顶按钮
在web开发中,页面常常会需要制作一个置顶按钮,因此我决定自己用jq做一个demo在此记录,方便日后重复使用;代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>置顶按钮</title>
<!-- 引入自己本地的jQuery文件 -->
<script src="../src/jquery-3.5.1.min.js"></script>
</head>
<style>
body {
background-image: linear-gradient(rgb(184, 111, 212), #e66465, #9198e5, rgb(255, 50, 98), rgb(50, 255, 228));
}
</style>
<body>
<h1>要滚动鼠标呀</h1>
</body>
<script>
// 创建置顶按钮
// 这里的div中的“Top”可以换成你喜欢的字体图标或者图片,例如那种向上的箭头图标等等;
var html = $('<div class="toTop">Top</div>');
//给body设置一个高度,便于滚动
$('body').css({
'height': '2600px',
'background-color': 'pink'
})
// 设置置顶按钮样式,也可在css中自定义
html.css({
'width': '40px',
'height': '60px',
'background-color': 'tomato',
'position': 'fixed',
'right': '0',
'bottom': '160px',
'display': 'none',
'text-align':'center'
});
$('body').append(html);
$(window).on('scroll', function() {
// 当页面滚动距离大于100时 淡入
if ($(window).scrollTop() > 100) {
html.fadeIn();
} else {
html.fadeOut();
}
});
html.on('click', function() {
$('body,html').animate({
scrollTop: 0,
// 设置置顶所需的时间200ms
}, 200)
});
</script>
</html>
好啦,现在就可以使用啦;