【发布时间】:2015-09-29 05:13:49
【问题描述】:
我有以下html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style>
.item {
width: 500px;
min-width: 500px;
background-color: brown;
padding: 10px;
border: 5px solid white;
display: inline-block;
}
.wrapper {
width:100%;
overflow-y:scroll;
white-space:nowrap;
}
</style>
</head>
<body>
<div class="wrapper">
<div id="me">
<div class="item">..</div>
<div class="item">..</div>
<div class="item">..</div>
<div class="item">..</div>
</div>
</div>
</body>
</html>
如果我尝试以下操作:
>screen.width
1440
>document.getElementById("me").getBoundingClientRect();
bottom: 56, height: 48, left: 8, right: 1415, top: 8, width: 1407
我希望宽度至少为 2000 (4X500) 加上填充等。
相反,它给了我屏幕宽度。我将使用可变数量的元素填充“me”元素,这些元素必须水平滚动并需要元素的宽度。
由于内容是可变的,我无法将其设置为固定值,而是希望将 100% 的屏幕宽度用于容器并计算内容的宽度(自定义滚动条所需的)。
感谢您抽出宝贵时间阅读此问题。
[更新]
至于阿尔瓦罗的出色回答;这是我计划使用的代码示例(对不起 jQuery):
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<style>
.item {
width: 470px;
min-width: 470px;
background-color: brown;
padding: 10px;
border: 5px solid white;
display: table-cell;
}
.wrapper {
width:100%;
overflow-y:scroll;
white-space:nowrap;
}
</style>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function(){
function addItem(){
$("#me").append('<div class="item">..</div>');
var box = $("#me")[0].getBoundingClientRect();
output(box);
}
function removeItem(){
$("#me .item").eq(0).remove();
var box = $("#me")[0].getBoundingClientRect();
output(box);
}
function output(box){
console.log("width is:",(box.left-box.right)*-1);
$("#output").html("width is:"+(box.left-box.right)*-1);
}
$("#ADD").on("click",addItem);
$("#REMOVE").on("click",removeItem);
})
</script>
</head>
<body>
<div class="wrapper">
<div id="me" style="float:left">
<div class="item">..</div>
<div class="item">..</div>
<div class="item">..</div>
<div class="item">..</div>
<div class="item">..</div>
<div class="item">..</div>
<div class="item">..</div>
<div class="item">..</div>
</div>
</div>
<div id="output"></div>
<input type="button" id="ADD" value="ADD" />
<input type="button" id="REMOVE" value="REMOVE" />
</body>
</html>
【问题讨论】:
标签: html css width horizontal-scrolling