zoukankan      html  css  js  c++  java
  • JS-JQ-滚动条回到顶部

    一、思路:

      得到document.documentElement.scrollTop的值,赋值为0

      documentElement :属性可返回文档的根节点

    二、知识

      $(window) 获取的是窗口
      $('body,html')获取的是文件本身

      $('html,body') 为什么要写2个,是因为 firefox ie 不支持 body, chrome 支持的是body, 所以为了兼容就这样写

    !!! - CSS

    <style>
      body{height:3000px;}
      #div1{50px;height:50px;box-sizing: border-box;background:rosybrown;position:fixed;
      _position:absolute;_top:expression(documentElement.scrollTop+"px");
      z-index:9999;bottom:30px;right:30px;}
    </style>

    !!! - HTML

    <div id="div1"></div>

    !!! - JavaScript

       基础版本:小白就看这个吧,这个是基础版本

    window.onload=function()

    {
      var div1=document.getElementById('div1');
      div1.onclick=function()
      {

        //FF:document.documentElement.scrollTop获取滚动条滚动的高度

        //IE:document.body.scrollTop获取滚动条滚动的高度
        document.documentElement.scrollTop=document.body.scrollTop=0;
      }
    }

       中等版本:这个有了动画效果

    window.onload=function()
    {
      var div1=document.getElementById('div1');
      var byse=true;
      var timer=null;
      window.onscroll=function()
      {
        if(!byse)    //如果回到顶部的时候byse=false,
        {
          clearInterval(timer);
        }
        byse=false;
      }

      div1.onclick=function()
      {
        timer=setInterval(function(){
          var s=document.documentElement.scrollTop||document.body.scrollTop;
          var iSpeed=Math.floor(-s/8);
          var timer=null;
          if(s==0)
          {
            clearInterval(timer);
          }
          byse=true;
          document.documentElement.scrollTop=document.body.scrollTop=s+iSpeed;
        },30);
      }
    }

    !!!- JQuery

    $(function(){
      $('#div1').bind('click',function(){
        var s=0;
        $('body,html').animate({
          scrollTop:s,
        },30)
      })
    })

  • 相关阅读:
    CRUD工程师——嵌入式Web容器
    CRUD工程师——SpringBoot启动原理
    CRUD工程师——日志
    CRUD工程师——慢SQL
    CRUD工程师——索引
    前端专业术语: shim 和 Polyfill,了解下
    H5之postMessage 。实现跨域
    摘抄详细的VUE生命周期
    如何在不使用三大地图的KEY和相关组件的情况下,直接传参数到相关的H5地图
    Mac下通过brew安装指定版本的nodejs
  • 原文地址:https://www.cnblogs.com/xiaoyangtian/p/7922196.html
Copyright © 2011-2022 走看看