zoukankan      html  css  js  c++  java
  • JS-JQ-垂直居中的侧边栏

    一、原理:

      滚动高度+(可视区高度-div高度的一半)/2

      JS:document.documentElement.scrollTop+(document.documentElement.clientHeight-div/2)/2

      JQ:$(window).scrollTop()+($(document).height()-div/2)/2

    二、知识

      $(document):获取整个网页的文档对象

      $(window):获取窗口对象,也就是浏览器客户区       是窗口

      $('body,html'):获取的是文件本身   是文档

    !!!- CSS

    <style>
      body{height:2000px;}
      *{margin:0;padding: 0;}
      #div1{200px;height:100px;background:red;position:absolute;top:0;bottom:0;}
    </style>

    !!! - HTML

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

    !!! - JavaScript

    window.onscroll=window.onload=function()
    {
      //1、垂直居中
      var div1=document.getElementById('div1');
      var w=document.documentElement.clientWidth||document.body.clientWidth;
      var h=document.documentElement.clientHeight||document.body.clientHeight;
      //2、滚动也能居中
      var Y=document.documentElement.scrollTop||document.body.scrollTop;
      div1.style.top=Y+(h-div1.offsetHeight/2)/2+"px";
    }

    !!! - JQuery

    //这个效果并没有完美,会发现DIV并不垂直居中,仅给朋友们参考

    $(function(){
      function ok()
      {
        var h=$(window).height();//可视区高度
        $('#div1').css('top',$(document).scrollTop()+(h-$(this).height()/2)/2);
      }
      ok();
      $(window).scroll(function(){
        ok();
      })
    })

  • 相关阅读:
    逃避是解决不了问题
    div包含table
    change is possible
    POI修改Excel
    要做的事情太多,把手边的事情做好。
    不自信,不努力
    添加省略号
    C#基类库
    如何做到在页面POSTBACK刷新后,使LISTBOX的滚动条仍然保持上次的位置
    安装dedecms后台登录空白的解决方法
  • 原文地址:https://www.cnblogs.com/xiaoyangtian/p/7922917.html
Copyright © 2011-2022 走看看