jquery中获取元素的位置和宽高

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        body{
            margin:50px;
           /**/


        }
        .wrap{
            width:300px;
            height: 300px;
            background-color: red;
            left:200px;
            position:relative;
            border:1px solid black;
            box-sizing: border-box;
        }
        .inner{
            position: absolute;
            width: 100px;
            height: 100px;
            left: 50px;
            background-color: blue;
           /* border:1px solid black;*/
            box-sizing: border-box;




        }
    </style>
    <script src="jquery.min.js"></script> 


</head>
<body>
<div class="wrap" id="wrap" style="left:200px;">
    <div class="inner" id="inner">
    </div>
</div>


<script type="text/javascript">
    console.log($(".wrap").css("left")); //200px /*如果父元素中有定位元素,都是相对于上一个定位元素(position不为static)定位。此处相对于body的左边,有单位 200px*/
    console.log($(".wrap").offset().left);//250    /*    它永远是相对于文档的左边缘(往往体现为浏览器的左边缘)定位的     没有单位    249.9999999 */
    console.log(document.getElementById("wrap").offsetLeft); //250 /*如果没有已经定位的父元素,那么offsetLeft指向的是文档(document)的左边缘   没有单位  250*/
    console.log(document.getElementById("wrap").style.left);  //200px /*style.left与css("left")指向的是body的左边缘*   有单位    200px*/
    console.log($(".inner").css("left"));    //50px /* 相对于上一个定位元素 50px  */
    console.log($(".inner").offset().left);   //301  /*文档的左边缘      没有单位  301  存在边框时会计算边框的大小*/    
    console.log(document.getElementById("inner").offsetLeft); //50  /*相对于上一级   没有单位 50*/
//    console.log("如果style.left没有在内联样式中指定:"+document.getElementById("inner").style.left);
console.log($(".inner").position().left);
//$(".inner").width(200);    //设置box-sizeing最后等于202  不设置的情况下还是等于202
//$(".inner").css("width",100) //不设置box-sizing最后等于102  设置了的情况下等于100    (符合实际理解)

console.log($(".inner").width());   //设置box-sizeing后等于98,不设置的情况下100
console.log($(".inner").css("width")); //设置box-sizeing后等于100px ,不设置的情况下 100px










</script>
</body>

</html>




总结:获取元素宽高时和设置宽高时,使用$().css("width");获取距离文档德距离使用$().offset().left;获取相对迁移位置时候使用$().position().left;


发现新的一篇比较好的文章 地址:https://www.cnblogs.com/muyun/p/3567235.html

猜你喜欢

转载自blog.csdn.net/qq_21729177/article/details/78488020
今日推荐