博客列表 >06 盒(或框)的属性、位置

06 盒(或框)的属性、位置

老黑
老黑原创
2020年06月18日 22:15:14592浏览

主要内容:盒的各种属性及位置定位、获取等

1、基本内容

  • 盒子的概念和属性:宽、高、大小。
  • 大小这块涉及到内容区、padding、border、margin等概念。相邻盒子的margin会重叠。
    (宽度width: content-width + padding-left/right + border-left/right - 注意除了内容区外,很多都需要两边都计算)
    box-sizing的两种状态。

    1. /* box-sizing: 重新计算盒大小; */
    2. /* content-box: 默认值,以内容区为准 */
    3. box-sizing: content-box;
    4. box-sizing: border-box; /*以边线区为大小,内容区的调整不会改变整体的大小*/

    border-box选项:
    为元素设定的宽度和高度决定了元素的边框盒。
    就是说,为元素指定的任何内边距和边框都将在已设定的宽度和高度内进行绘制。
    通过从已设定的宽度和高度分别减去边框和内边距才能得到内容的宽度和高度。

  • 定位。绝对定位和相对定位postion:relative;postion:absolute。

  • 盒子的父子关系。
  • 怎么显示出padding。background-clip: content-box;
  • 初始清零有些时候很关键。
    1. * {
    2. margin: 0;
    3. padding: 0;
    4. box-sizing: border-box;
    5. }

    2、垂直、水平居中

    1. position: absolute;
    2. /* 让当前元素绝对定位的上下文充满整个父级容器 */
    3. /* 左上角开始 */
    4. top: 0;
    5. left: 0;
    6. /* 右下角结束 */
    7. right: 0;
    8. bottom: 0;
    9. /* 水平垂直居中 */
    10. margin: auto;
    当然这块老师也介绍了flex之类的东东,但现在还没学到。

3、大小位置的获取

  1. <script>
  2. const box = document.querySelector(".box");
  3. // 1. 内容区大小与位置
  4. // 大小 = width / height + padding
  5. console.log(box.clientWidth);
  6. console.log(box.clientHeight);
  7. // clientLeft/clientTop: 表示的padding到border外边缘的距离: 就是边框宽度
  8. // 用得极少, 忘了我吧
  9. console.log(box.clientLeft);
  10. console.log(box.clientTop);
  11. // 更多的时候用来获取可视区大小: 视口
  12. console.log(document.documentElement.clientWidth);
  13. console.log(document.documentElement.clientHeight);
  14. // 2. 当前元素的定位偏移量,与定位有关
  15. // 定位父级
  16. console.log(box.offsetParent);
  17. // 这个元素现在是一个真正的盒子,包括了内容,padding, border
  18. // 真实宽度: 加上border
  19. console.log(box.offsetWidth);
  20. console.log(box.offsetHeight);
  21. console.log(box.offsetLeft);
  22. console.log(box.offsetTop);
  23. // 3. 当前文件的滚动大小
  24. // 视口大小: 可视区大小
  25. // 文档大小: 当前html的大小
  26. // 通过视口大小 < 文档大小, 所以,要通过滚动条才能看到全部html文档的内容
  27. // 获取html元素
  28. const html = document.documentElement;
  29. html.style.height = "600px";
  30. // 当前文档的高度
  31. console.log(html.scrollHeight);
  32. // 当前可视区的高度
  33. console.log(html.clientHeight);
  34. // 获取滚动条
  35. // 234 + 366 = 600
  36. console.log(html.scrollTop);
  37. document.addEventListener("scroll", function (ev) {
  38. console.log(ev.target.documentElement.scrollTop);
  39. });
  40. </script>

可以通过改变元素位置的方式来做一些动画。例如下面这个function通过增加图片的上下位置,实现图片向右下角移动的目的。

  1. // 定时器
  2. let timer = null;
  3. function start() {
  4. console.log(thief.offsetLeft);
  5. timer = setInterval(function () {
  6. // thief.offsetLeft: 只读, 且是一个整数
  7. // thief.style.left: 可读写,且是一个字符串
  8. thief.style.left = thief.offsetLeft + 10 + "px";
  9. thief.style.top = thief.offsetTop + 10 + "px";
  10. }, 100);
  11. }
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议