jq实现新闻无限滚动外加回到顶部功能

一.html

  <ul class="new-list">

  </ul>
  <button>回到顶部</button>

二.css

*{
  padding:0;
  margin:0;
  list-style:none;
}
a{
  text-decoration: none;
}
.clearfix::after{
  content: "";
  clear: both;
  display: block;
  width:0;
  height: 0;
}
.new-list,.btns{
  width:500px;
  margin:50px auto;
}
.new-list li{
  border-bottom: 1px solid gainsboro;
  padding:20px 0;
}
.new-list li:last-child{
  border-bottom:none;
}
.new-list li img{
  float: left;
  width: 100px;
  margin-right: 10px;
} 
.news-dec p{
  color:gainsboro;
}
button{
  position: fixed;
  bottom: 10px;
  right: 10px;
  background: red;
}

三.script

     var pageNums=1;
    getList(pageNums);

    // 滚动条事件
    $(window).scroll(function(){
      var scrollTop = $(this).scrollTop();
      var windowHeight = $(this).height();
      var scrollHeight = $(document).height();
      // console.log(scrollTop+windowHeight);
      // console.log(scrollHeight);
     if(scrollTop+windowHeight>=scrollHeight){
        pageNums++
        getList(pageNums)
      } 
    })
    // 回到顶部按钮
    $("button").click(function(){
      $("html").animate({
       "scrollTop":"0",
      },1000)
    })


  //函数封装 
  function getList(pageNums){
  $.ajax({
    url:"https://api.apiopen.top/getWangYiNews",
    method:"POST",
    data:{
      page:pageNums,
      count:10,
    },
    success:function(res){
      // console.log(res);
      if(res.code===200){
        // $(".new-list").html("");
        for(var i=0;i<res.result.length;i++){
          var item=res.result[i];
          var str='<li class="clearfix">'+
                    '<img src="'+item.image+'" alt="断网了">'+
                    '<div class="news-dec">'+
                      '<h3>'+item.title+'</h3>'+
                      '<p>'+item.passtime+'</p>'+
                    '</div>'+
                  '</li>'
         $(".new-list").append(str);        
        }
      }
    }
  })  
  }
发布了53 篇原创文章 · 获赞 76 · 访问量 1689

猜你喜欢

转载自blog.csdn.net/weixin_45389051/article/details/104704389