在flexbox定位的元素的左侧和顶部

时间:2018-10-16 18:34:04

标签: javascript html css flexbox

当使用flexbox布置元素时,我想知道它们相对于窗口的顶部和左侧。

这可能吗?

使用window.getComputedStyle会同时返回autotop属性的left

const cells = document.querySelectorAll('.cell')

cells.forEach(cell => {
  cell.addEventListener('click', function(event) {
    const cell = event.target;
    const left = getComputedStyle(cell).left;
    const top = getComputedStyle(cell).top;
    document.getElementById('display').innerHTML = 'Left: ' + left + ' - Top: ' + top;
  });
})
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 50vh;
  margin: 0 auto;
  justify-content: center;
  align-items: center;
}

.container .row {
  display: flex;
}

:root {
  --cell-size: 20px;
}

.container .row .cell {
  width: var(--cell-size);
  height: var(--cell-size);
  background-color: steelblue;
  border: 1px #ccc solid;
  border-radius: 100%;
  margin: calc(var(--cell-size) / 4);
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>CSS Animation demo</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="container">
    <div>Click a flex child to see its computed top and left</div>
    <div id="display">&nbsp;</div>
    <div class="row">
      <div class="cell"></div>
      <div class="cell"></div>
      <div class="cell"></div>
      <div class="cell"></div>
      <div class="cell"></div>
      <div class="cell"></div>
    </div>
  </div>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

您想要.offsetLeft.offsetTop

const cells = document.querySelectorAll('.cell')

cells.forEach(cell => {
  cell.addEventListener('click', function(event) {
    const cell = event.target;
    const left = cell.offsetLeft;
    const top = cell.offsetTop;
    document.getElementById('display').innerHTML = 'Left: ' + left + ' - Top: ' + top;
  });
})
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 50vh;
  margin: 0 auto;
  justify-content: center;
  align-items: center;
}

.container .row {
  display: flex;
}

:root {
  --cell-size: 20px;
}

.container .row .cell {
  width: var(--cell-size);
  height: var(--cell-size);
  background-color: steelblue;
  border: 1px #ccc solid;
  border-radius: 100%;
  margin: calc(var(--cell-size) / 4);
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>CSS Animation demo</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="container">
    <div>Click a flex child to see its computed top and left</div>
    <div id="display">&nbsp;</div>
    <div class="row">
      <div class="cell"></div>
      <div class="cell"></div>
      <div class="cell"></div>
      <div class="cell"></div>
      <div class="cell"></div>
      <div class="cell"></div>
    </div>
  </div>
</body>
</html>