• jQuery获取元素的大小和位置信息


    先贴出元素模型信息

    1.css()方法获取元素的宽高

    css()方法返回的其实是getComputedStyle(node).width的值,也就是元素内容区的宽高
    注意:这个是带单位的

    <script>
        $(function(){
            console.log($("div").css("width"))
            console.log($("div").css("height"))
        })
    </script>

    运行结果:

    200px
    200px

    2.width() / height()

    这两个方法返回的也是元素内容区的宽高,但是不带单位

    <script>
        $(function(){
            console.log($("div").width())
            console.log($("div").height())
        })
    </script>

    运行结果:

    200
    200

    3.innerWidth() innerHeight()

    这两个方法返回的元素 内容区+内边距 的大小,即:
    width+padding / height + padding

    <script>
        $(function(){
            console.log($("div").innerWidth()) 
            console.log($("div").innerHeight())
        })
    </script>

    运行结果:

    240
    240

    4.outerWidth() outerHeight()

    这两个方法返回的元素 内容区+内边距+边框 的大小,即:width+padding+border / height + padding+border

    <script>
        $(function(){
            console.log($("div").outerWidth())
            console.log($("div").outerHeight())
        })
    </script>

    运行结果:

    260
    260

    5.outerWidth(true) outerHeight(true)

    返回元素 内容区+内边距+边框+外边距 的大小

    <script>
        $(function(){
            console.log($("div").outerWidth(true))
            console.log($("div").outerHeight(true))
        })
    </script>

    运行结果:

    646.6659999999999
    300

    2.元素的位置信息

    1.position() 返回包含元素的位置的对象(相对于父级定位元素)

    如果当前元素使用了绝对定位,则这个对象的值为它设置的top/left的值。如果当前元素没有绝对定位,则返回它父级定位元素的距离(当前元素边框到父级定位元素边框的距离)的对象

    <body>
        <div id="box">定位父元素
            <div>非定位元素
                <div>当前元素</div>
            </div>
        </div>
    </body>
    <script>
        $(function(){
            console.log($(".child").position())
        })
    </script>

    控制台打印:

    {top: 87, left: 120}

    资源搜索网站大全 http://www.szhdn.com

    2.offset( 返回当前元素相对于document位置距离的对象

    返回当前元素与浏览器边框的绝对距离的对象,即:如果body有滚动条,要加上被body滚动条隐藏的距离

    <script>
        $(function(){
            console.log($(".child").offset()) //{top: 157, left: 283}
        })
    </script>

    3.获取和设置被滚动条卷去的宽度和高度 scrollLeft()/scrollTop()

    当前元素必须有滚动条,也就是说他的子元素大小要比他大,这样滚动条才能滚动

    //获取被滚动条卷去的宽度和高度
    $('.box').scrollLeft();
    $('.box').scrollTop();
    
    //设置滚动条位置(页面回到顶部)
    $(window).scrollLeft(0);
    $(window).scrollTop(0);
  • 相关阅读:
    jQuery笔记之工具方法—Ajax 优化回调地狱
    jQuery笔记之工具方法—高级方法Ajax
    jQuery笔记之 Ajax回调地狱
    jQuery笔记之工具方法extend插件扩展
    jQuery同时监听两个事件---实现同时操控两个按键
    jQuery笔记之工具方法
    肖sir_多测师 _高级讲师 第二个月21讲解jmeter性能测试之安装badboy(002)
    肖sir_多测师 _高级讲师 第二个月21讲解jmeter之实战性能测试(001)
    肖sir_多测师 _高级讲师 第二个月20讲解jmeter之实战操作mysql(004)
    肖sir_多测师 _高级讲师 第二个月20讲解jmeter接口之实战(003)
  • 原文地址:https://www.cnblogs.com/xiaonian8/p/14024885.html
Copyright © 2020-2023  润新知