专业编程基础技术教程

网站首页 > 基础教程 正文

使用jquery实现返回顶部滑动效果实例

ccvgpt 2024-11-06 16:49:10 基础教程 23 ℃

jQuery点击返回顶部的功能在网页中很常见。当网站内容过多的时候,添加一个返回顶部的功能,可以更好的增加用户体验。用jQuery写了这样一个效果。

返回顶部按钮的一些css样式,如下:

使用jquery实现返回顶部滑动效果实例

.last{

position: fixed;

width: 50px;

height: 50px;

right: 200px;

bottom: 55px;

cursor: pointer;

text-align: center;

line-height: 50px;

background-color: #00b7ee;

opacity: 0.8;

color: #fff;

}

.last:hover{

background-color: #1fb5ad;

color: #fff;

}

首先需要在html页面添加如下元素:

<!--返回顶部 start-->

<div class="last">

<span> 顶部 </span>

</div>

<!--返回顶部 end-->

jquery代码

有了html和样式,我们还需要用jquery来控制返回顶部按钮,在页面滚动时淡入淡出返回顶部按钮。

<script>

$(document).ready(function() {

//首先将.last 隐藏

$(".last").hide();

//当滚动条的位置处于距顶部150像素以下时,返回顶部按钮显示,否则隐藏

$(function() {

$(window).scroll(function() {

if ($(window).scrollTop() > 150) {

$(".last").fadeIn(1500);

} else {

$(".last").fadeOut(1500);

}

});

// 点击返回顶部

$('.last').on('click',function(){

$('html,body').animate({

scrollTop:0

},500);

return false;

});

});

});

</script>

Tags:

最近发表
标签列表