对于初识jQuery的小伙伴来说,还是一个比较不错的demo小例子吧。可以拿来练练手。
接下来上代码啦。。。
html+css代码:
(Ps:为方便,我把CSS+HTML代码放在了一起。用分割线用来区别。)
<style> .divH{ height: 2000px; } .divT{ width: 45px; height: 45px; font-size: 18px; background-color:yellow; color: white; position: fixed; right: 18px; bottom: 18px; } .divT:hover{ cursor: pointer; background-color:lightblue; } .hide{ display: none; } </style>
<div class="divH"></div> <div class="divT hide" onclick="ReturnTop();"><strong>返回顶部</strong></div>
jQuery代码:
<script> window.onscroll=function () { const current=$(window).scrollTop(); if(current>180){ $(".divT").removeClass("hide"); }else{ $(".divT").addClass("hide"); } }; function ReturnTop() { $(window).scrollTop(0); }
</script>
有些小伙伴可能复制+粘贴代码的时候不成功。
那是为什么呢?原因是你没有导入jQuery库啦。这一步千万不能忘记哦(*^▽^*)
第一次写博客,内心还有一丝小雀跃呢(〃'▽'〃)