当使用flexbox布置元素时,我想知道它们相对于窗口的顶部和左侧。
这可能吗?
使用window.getComputedStyle
会同时返回auto
和top
属性的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"> </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>
答案 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"> </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>