在下面的示例代码中,类为
.carousel
的元素设置为具有 width: 500px
,但 clientWidth 报告的宽度为 471
。我可以通过将 .arrow
的填充值设置为像素值而不是百分比来解决此问题,然后 clientWidth 会正确报告 500
。这是一个错误还是我不明白什么?
当
.arrow
填充设置为百分比时,无论我使用什么JS函数,我似乎都无法得到500
。
这是在 Safari 中,未在其他地方测试过。
document.addEventListener("DOMContentLoaded", (event) => {
console.log(document.getElementById("width-inspect").offsetWidth);
});
body, html {
background: black;
}
.flex-row {
flex-direction: row;
display: flex;
}
.carousel-right-box {
max-width: 1024px;
margin-left: 25px;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
.carousel {
position: relative;
height: 680px;
width: 500px;
margin: 0 auto;
}
.carousel-content {
position: relative;
overflow: hidden;
height: 100%;
width: 100%;
}
.arrow {
padding: 1%;
}
<div class="flex-row">
<div class="carousel-right-box">
<button class='arrow'>
<img src="./images/left-arrow.png">
</button>
<div class="carousel">
<div id="width-inspect" class="carousel-content">
</div>
</div>
<button class='arrow'>
<img src="./images/right-arrow.png">
</button>
</div>
</div>
我将您的代码转换为可重现的示例。
您应该添加
.carousel { flex-shrink: 0; }
或 flex: none;
,这样它就不会缩小。
document.addEventListener("DOMContentLoaded", (event) => {
console.log(document.getElementById("width-inspect").offsetWidth);
});
*{
box-sizing: border-box;
}
body, html {
background: black;
}
.flex-row {
flex-direction: row;
display: flex;
}
.carousel-right-box {
max-width: 1024px;
margin-left: 25px;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
.carousel {
position: relative;
height: 680px;
width: 500px;
margin: 0 auto;
flex: none; /* <- */
}
.carousel-content {
position: relative;
overflow: hidden;
height: 100%;
width: 100%;
}
.arrow {
padding: 1%;
}
<div class="flex-row">
<div class="carousel-right-box">
<button class='arrow'>
<img src="./images/left-arrow.png">
</button>
<div class="carousel">
<div id="width-inspect" class="carousel-content">
</div>
</div>
<button class='arrow'>
<img src="./images/right-arrow.png">
</button>
</div>
</div>