gpt4 book ai didi

javascript - 获取 flexbox 定位元素的左侧和顶部

转载 作者:行者123 更新时间:2023-11-30 11:13:06 25 4
gpt4 key购买 nike

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

这可能吗?

使用 window.getComputedStyletopleft 属性返回 auto

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>

最佳答案

你想要 .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>

关于javascript - 获取 flexbox 定位元素的左侧和顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52841934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com