您当前的位置: 首页 >  Java

柠檬味小发糕

暂无认证

  • 3浏览

    0关注

    84博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

JavaScript基础学习 offsetLeft和offsetTop获取元素偏移

柠檬味小发糕 发布时间:2021-12-23 21:09:39 ,浏览量:3

JavaScript基础学习 offsetLeft和offsetTop获取元素偏移
  • offset与style的区别





    
    
    
    Document
    
        * {
            margin: 0;
            padding: 0;
        }
        
        #father {
            position: absolute;
            width: 200px;
            height: 200px;
            background-color: blueviolet;
            margin: 100px;
        }
        
        #son {
            width: 100px;
            height: 100px;
            background-color: red;
            margin-top: 10px;
            margin-left: 20px;
        }
        
        .w {
            height: 200px;
            background-color: skyblue;
            margin: 0 auto 200px;
            padding: 10px;
            border: 15px solid red;
        }
    



    
var father = document.querySelector('#father'); // father的div相对于body上方偏移的像素 console.log(father.offsetTop); // father的div相对于body左方偏移的像素 console.log(father.offsetLeft); console.log('-----------------------------------------------'); var son = document.querySelector('#son'); // son的div相对于father左方偏移的像素 // 得到这样的数据前提是father的div是绝对定位,否则得到的是son的div相对于body左方偏移的像素 console.log(son.offsetLeft); // 20 // son的div相对于father上方偏移的像素 console.log(son.offsetTop); // 10 console.log('-----------------------------------------------'); var w = document.querySelector('.w'); // 2.可以得到元素的大小 宽度和高度 是包含padding + border + width console.log(w.offsetWidth); console.log(w.offsetHeight); // 3. 返回带有定位的父亲 否则返回的是body console.log(son.offsetParent); // 返回带有定位的父亲 否则返回的是body console.log(son.parentNode); // 返回父亲 是最近一级的父亲 亲爸爸 不管父亲有没有定位
offset与style的区别




    
    
    
    Document
    
        .box {
            width: 200px;
            height: 200px;
            background-color: pink;
            padding: 10px;
        }
    



    
// offset与style的区别 // offset能够获取元素的任意样式表中的样式值 而style只能获取行内样式表当中的样式值 var box = document.querySelector('.box'); console.log(box.offsetWidth); console.log(box.style.width); // box.offsetWidth = '300px'; // 我们想要给元素更改样式值,使用style更合适 box.style.width = '300px';
关注
打赏
1640351950
查看更多评论
立即登录/注册

微信扫码登录

0.0378s