【问题标题】:How to set width of a div to fit the contents?如何设置 div 的宽度以适应内容?
【发布时间】:2013-10-16 23:13:50
【问题描述】:

我已经搜索了一整天,但我找不到我想做的事情的解决方案。我知道这个标题有很多问题,但没有一个对我有用。

我想做的是移动设备的触摸滚动。

这是我的html:

    <body>
    <div id="slider_container"> 
         <div class="wrapper">
             <span>Image</span>
         </div>
    </div>
    </body>

至少有 2 个 span 包含图像,最多 10 个 span 包含图像。会有一些php代码和span number会根据用户上传的照片而改变。

这是我的css代码:

body
{
      width:100%;
      overflow-x:hidden;
}

#slider_container
{
width:100%;
height:320px;
overflow: scroll;
overflow-y: hidden;
-webkit-overflow-scrolling: touch;
}

.wrapper
{
position:absolute;
height:320px;
}

.wrapper img
{
max-width:310px;
max-height:310px;
margin-right:5px;
float:left;
}

我想要的是让 .wrapper 自动宽度并溢出 #slider_container 和 body 之外。

希望我能说清楚。

感谢所有回答...

【问题讨论】:

标签: html css


【解决方案1】:

您必须使用 JavaScript 来测量内容,然后相应地设置包装器的宽度。像这样的:

var spans = document.querySelectorAll('.wrapper span');
var width = 0;
for(var i=0; i<spans.length; i++) {
    width += spans[i].offsetWidth + 5; // + 5 for the margins
}
document.querySelector('.wrapper').style.width = width + 'px';

多个滑块的替代代码:

var wrappers = document.querySelectorAll('.wrapper');
var width;
for(var i=0; i<wrappers.length; i++) {
    var spans = wrappers[i].querySelectorAll('span');
    width = 0;
    for(var j=0; j<spans.length; j++) {
        width += spans[j].offsetWidth + 5; // + 5 for the margins
    }
    wrappers[i].style.width = width + 'px';
}

http://jsfiddle.net/s4RxE/1

【讨论】:

  • 感谢您的回答。这有助于页面上的第一个滑块。对于其他人来说,它没有用。因此,我将
    更改为
    id 将是一个变量,并且页面上的每张幻灯片都有其唯一的 id 作为数字。我应该如何更改 javascript 代码以使其适用于每张幻灯片?非常感谢您的回答,但我对 javascript 了解不多。
猜你喜欢
  • 1970-01-01
  • 2023-03-11
  • 2022-11-30
  • 1970-01-01
  • 1970-01-01
  • 2020-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多