zoukankan      html  css  js  c++  java
  • 通用垂直居中方法兼容各浏览器改进

    之前写了一篇“拍脑门”得来的在各浏览器都能垂直居中的方法,要兼容各大浏览器,真的不得不借助脚本(JQuery已经使写脚本跟写CSS差不多了),大体思路就是取得要被居中元素的高度和其容器的高度,计算根据两个高度差计算出一个top来,随手写来,测试全部通过,不过事后一样,之前的脚本应该改良一下,不多说,直接给代码:

    之前的实现方法:

        <script src="scripts/jquery.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(
    function () {
                FixIt_Vertically(
    "div1");
            });
            
    function FixIt_Vertically(id) {

                var myheight = $("#" + id).outerHeight();
                
    var myfatherheight = $("#" + id).parent().height();
                
    var mytop = (myfatherheight - myheight) / 2;
                $(
    "#" + id).css("position""relative").css("top", mytop + "px");
            }
        
    </script>

    改良后的代码:

        <script src="scripts/jquery.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(
    function () {
                FixIt_Vertically(
    "vertically");
            });
            
    function FixIt_Vertically(theclass) {
                $("." + theclass).each(function () {
                    myheight 
    = $(this).outerHeight();
                    myfatherheight 
    = $(this).parent().height();
                    mytop 
    = (myfatherheight - myheight) / 2;
                    $(
    this).css({ "position""relative""top": mytop });
                });
            }
        
    </script>

    看出来了吧?改进的地方就是把原来的id改成了class,这样,只要给每一个要垂直居中的元素加上一个vertically类(class="vertically"),就OK了。

    附:

    实际使用中再发现什么问题我再来改。

    感谢@吝啬你的温柔



  • 相关阅读:
    (树的直径)第九届湘潭市大学生程序设计比赛 H-Highway
    (记忆化DFS)Codeforces Round #413 D-Field expansion
    (树状数组)Codeforces Round #413 C-Fountains
    (几何)LeetCode Weekly Contest 32 D-Erect the Fence
    LeetCode Weekly Contest 32 解题报告
    (贪心)华师大程序设计竞赛 F-丽娃河的狼人传说
    (最短路)AtCoder Beginner Contest 061 D
    Tinkoff Challenge
    Codeforces Round #410 (Div. 2) 解题报告
    (二叉树)UVA
  • 原文地址:https://www.cnblogs.com/chenqiang001/p/2316829.html
Copyright © 2011-2022 走看看