jQuery-尺寸、位置操作

jQuery尺寸

语法 用法
width() / height() 取得匹配元素宽度和高度值,只算width/height
innerWidth() / innerHeight() 取得匹配元素宽度和高度值,包含 padding
outerWidth() / outerHeight() 取得匹配元素宽度和高度值,包含padding、border
outerWidth(true) / outerHeight(true) 取得匹配元素宽度和高度值,包含padding、border、margin

  以上参数为空,则是获取相应值,返回的数字型。

  如果参数为数字,则是修改相应值。

复制代码
  <style>
    div {
      width: 200px;
      height: 200px;
      background-color: cyan;
      padding: 10px;
      border: 15px solid black;
      margin: 20px;
    }
  </style>
</head>

<body>
  <div></div>
</body>
<script src="./jquery.min.js"></script>
<script>
  console.log($('div').width());
  console.log($('div').innerWidth());
  console.log($('div').outerWidth());
  console.log($('div').outerWidth(true));
</script>
复制代码

jQuery 位置

  主要有三个:offset()、position()、scrollTop() / scrollLeft()。

  offset:设置或获取元素偏移。

    1、设置或返回被选元素相对于文档的偏移坐标,跟父级没有关系。

    2、该方法有两个属性,left 和 top。offset().top 用于获取距离文档顶部的距离,offset().left 用于获取距离文档左侧的距离。

    3、可以设置元素的偏移:offset({top:10, left:20})

  position:获取元素偏移。

    1、position() 方法用于返回被选元素相对于带有定位的父级偏移坐标,如果父级都没有定位,则以文档为准。

    2、这个方法只能获取不能设置。

复制代码
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .father {
      width: 400px;
      height: 400px;
      background: cyan;
      margin: 100px;
      overflow: hidden;
      position: relative;
    }

    .son {
      width: 150px;
      height: 150px;
      background: purple;
      position: absolute;
      top: 10px;
      left: 10px;
    }
  </style>
</head>

<body>
  <div class="father">
    <div class="son"></div>
  </div>
</body>
<script src="./jquery.min.js"></script>
<script>
  // 返回的是一个对象
  console.log($('.son').offset());
  console.log($('.son').offset().left);
  // $('.son').offset({
  //   top: 55,
  //   left: 333
  // })
  // 距离有定位的父级的距离,如果没有以body为准
  console.log($('.son').position());
</script>
复制代码

 

  scrollTop() / scrollLeft():设置或获取元素被卷去的头部和左侧。

    1、scrollTop() 方法设置或返回被选元素被卷去的头部。

复制代码
  <style>
    body {
      height: 2000px;
    }

    .back {
      position: fixed;
      width: 50px;
      height: 50px;
      background-color: cyan;
      right: 30px;
      bottom: 100px;
      display: none;
    }

    .container {
      width: 900px;
      height: 500px;
      background-color: skyblue;
      margin: 400px auto;
    }
  </style>
</head>

<body>
  <div class="back">返回顶部</div>
  <div class="container">
  </div>
</body>
<script src="./jquery.min.js"></script>
<script>
  $(window).scroll(function () {
    if ($(document).scrollTop() >= $('.container').offset().top) {
      $('.back').fadeIn()
    } else {
      $('.back').fadeOut()
    }
  })
</script>
复制代码

 

posted @   守鹤  阅读(86)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
点击右上角即可分享
微信分享提示