20190530 div-拖动drag(二)

下面列表中罗列的是dom元素和事件中的尺寸,在各类计算位置的方法中均有使用,须要十分熟悉。

------------------- >>>>>分割线<<<<< --------------javascript

elment元素自带的属性

尺寸 对应于style的属性 备注
offsetWidth width + 2 * borderWidth 宽度+边框*2
offsetHeight height + 2 * borderWidth 高度+边框*2
offsetTop top 相对于父元素(拖拽中用于获取当前元素的位置)
offsetLeft left 相对于父元素(拖拽中用于获取当前元素的位置)
clientWidth width 元素内部宽度
clientHeight height 元素内部高度

getBoundingClientRect() --> 一个神奇的api

尺寸 计算 备注
width offsetWidth 元素总体宽度
height offsetHeight 元素总体高度
top offsetTop(父元素) + boderWidth(父元素) + offsetTop 相对于视口的位置
left offsetLeft(父元素) + boderWidth(父元素) + offsetLeft
right left + offsetWidth
bottom top + offsetHeight
x left  
y top  

来自mdn的图

event对象上的尺寸

尺寸 说明
clientX、clientY 提供事件发生时的应用客户端区域的水平、垂直坐标 (与页面坐标不一样)---用于计算鼠标点的位置
layerX、layerY 鼠标相对于父元素外边缘的位置
offsetX、offsetY 鼠标相对于父元素内边缘的位置事件对象与目标节点的内填充边(padding edge)在 X、Y轴方向上的偏移量
pageX、pageY 基于文档的边缘,考虑任何页面的水平、垂直方向上的滚动。
screenX、screenY 鼠标相对于屏幕坐标系的水平、垂直偏移量
x、y clientX、clientY 属性的别名.

尺寸

------------------- >>>>>分割线<<<<< --------------css

各类教程中都曾出现的神图

------------------- >>>>>分割线<<<<< --------------html

代码仍是得敲才能搞明白,眼睛记不住。因此,请复制下面的代码,而后根据位置在纸上算一算java

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>drag</title>
  <style> * { margin: 0; padding: 0; } #container { border: 1px solid #000; position: absolute; left: 30px; top: 50px; width: 1000px; height: 800px; } #dragEl { position: absolute; width: 50px; height: 50px; border: 1px solid #000; left: 10px; top: 10px; } </style>
</head>
<body>
<div style="position: relative;height: 1000px">
  <div id="container">
    <div id="dragEl"></div>
  </div>
</div>
</body>
</html>
<script> const dragEl = document.getElementById('dragEl'); const { offsetLeft, // 10 ===> 相对于父元素 offsetTop, // 10 ===> 相对于父元素 offsetWidth, // 52 ==> 加边框宽度 offsetHeight, // 52 ==> 加边框宽度 clientWidth, // 50 ===> 不包含边框 clientHeight, // 50 ===> 不包含边框 } = dragEl; console.log(dragEl.offsetParent); // 获取当前元素的位置+尺寸信息 // width: 52 ===> offsetWidth // height: 52 ===> offsetHeight // top: 61 ====> 50 + 1(父元素边宽) + 10 // left: 41 ===> 30 + 1(父元素边宽) + 10 // right: 93 ====> 41(left) + 50 + 2(本身的边宽) // bottom: 113 ====> 61(top) + 50 + 2(本身的边宽) // x: 41 = left // y: 61 = top const dragElRect = dragEl.getBoundingClientRect(); /* * 点击event上的尺寸数据: * 提供事件发生时的应用客户端区域的水平、垂直坐标 (与页面坐标不一样) * clientX: 73 = 32(layerX) + 41(left) * clientY: 90 = 29(layerY) + 61(top) * * 鼠标相对于父元素外边缘的位置 * layerX: 32 * layerY: 29 * * 鼠标相对于父元素内边缘的位置 * 事件对象与目标节点的内填充边(padding edge)在 X、Y轴方向上的偏移量 * offsetX: 31 * offsetY: 28 * * 基于文档的边缘,考虑任何页面的水平、垂直方向上的滚动。 * pageX: 73 * pageY: 90 * * 鼠标相对于屏幕坐标系的水平、垂直偏移量 * screenX: 73 * screenY: 161 * * clientX、clientY 属性的别名. * x: 73 * y: 90 * * */ dragEl.addEventListener('mousedown', function (e) { console.log(e); }); </script>
复制代码
相关文章
相关标签/搜索