ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

jQuery之offset和position

2021-11-15 23:34:35  阅读:165  来源: 互联网

标签:jQuery top offset 左上角 position div2 div1


<!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 相对于父元素左上角的位置,div2的父元素就是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
  })

//设置div2相对于整个页面左上角的位置,
  $('#btn2').click(function () {
    $('.div2').offset({
      left: 50,
      top: 100
    })
  })
</script>
</body>
</html>

界面:

 

 点击设置offset按钮之后:

 

标签:jQuery,top,offset,左上角,position,div2,div1
来源: https://www.cnblogs.com/anjingdian/p/15559089.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有