jQuery 之 offset和position

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>12_offset和position</title>
</head>
<style type="text/css">
    * {
        margin: 0px;
    }

    .div1 {
        position: absolute;
        width: 200px;
        height: 200px;
        top: 20px;
        left: 10px;
        background: blue;
    }

    .div2 {
        position: absolute;
        width: 100px;
        height: 100px;
        top: 50px;
        background: red;
    }

    .div3 {
        position: absolute;
        top: 250px;
    }
</style>
<body style="height: 2000px;">

<div class="div1">
    <div class="div2">测试offset</div>
</div>

<div class='div3'>
    <button id="btn1">读取offset和position</button>
    <button id="btn2">设置offset</button>
</div>

<!--
获取/设置标签的位置数据
  * offset(): 相对页面左上角的坐标
  * position(): 相对于父元素左上角的坐标
-->
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript">
    /*
    需求:
    1. 点击 btn1
      打印 div1 相对于页面左上角的位置
      打印 div2 相对于页面左上角的位置
      打印 div1 相对于父元素左上角的位置
      打印 div2 相对于父元素左上角的位置
    2. 点击 btn2
      设置 div2 相对于页面的左上角的位置
     */
    $('#btn1').click(function () {
//    打印 div1 相对于页面左上角的位置
        var offset = $('.div1').offset()
        console.log(offset.left, offset.top) // 10 20
//    打印 div2 相对于页面左上角的位置
        offset = $('.div2').offset()
        console.log(offset.left, offset.top) // 10 70
//    打印 div1 相对于父元素左上角的位置
        var position = $('.div1').position()
        console.log(position.left, position.top) // 10 20
//    打印 div2 相对于父元素左上角的位置
        position = $('.div2').position()
        console.log(position.left, position.top) // 0 50
    })

    $('#btn2').click(function () {
        $('.div2').offset({
            left: 50,
            top: 100
        })
    })
</script>
</body>
</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值