如何获得图像的高度并将该高度应用于div?

时间:2012-11-13 19:26:29

标签: css jquery mobile

我正在构建一个移动网络应用程序,我正在使用jquerytools滑块。

我希望te滑块在所有移动设备上显示(以适当的比例),因此图像的宽度为100%,高度为css中的自动高度。但是,由于所有元素都是浮动的并且jquerytools滑块需要将位置设置为绝对,因此包含div(#header)不会拉伸以适合内容。

我正在尝试使用jquery来获取img高度的高度并将该高度应用于标题....但是我没有运气。

CSS:

    #header{
width:100%;
position:relative;
z-index: 20;
/* box-shadow: 0 0 10px white; */
overflow: auto;
}

.scrollable {
position:relative;
overflow:hidden;
width: 100%;
height: 100%;
/* box-shadow: 0 0 20px purple; */
/*  height:198px; */
z-index: 20;
overflow: auto;
}


.scrollable .items {
/* this cannot be too large */
width:1000%;
position:absolute;
clear:both;
/* box-shadow: 0 0 30px green; */

}

.items div {
float:left;
width:10%;
height:100%;

}

/* single scrollable item */
.scrollable img {
    /* float:left; */
    width:100%;
   height: auto;
 /*    height:198px; */
}

/* active item */
.scrollable .active {
    border:2px solid #000;
    position:relative;
    cursor:default;
}

HTML

    <div id=header><!-- root element for scrollable -->
    <div class="scrollable" id="scrollable">

      <!-- root element for the items -->
      <div class="items">


        <div>
          <img src="img/img2.jpg" />
        </div>


        <div>
           <img src="img/img1.jpg" />
        </div>


        <div>
         <img src="img/img3.jpg" />
        </div>

        <div>
         <img src="img/img4.jpg" />
        </div>

        <div>
         <img src="img/img6.jpg" />
        </div>

    </div><!-- items -->

    </div><!-- scrollable -->

    </div><!-- header -->

2 个答案:

答案 0 :(得分:1)

像这样:

var height = $('#myImageID').height();
$('#header').height(height);

http://api.jquery.com/height/

答案 1 :(得分:1)

我找到了解决方案。 Sdespont提供的代码非常完美,它引导我找到答案。他的代码显示零高度的原因是因为它在图像加载之前寻找图像高度。为了解决这个问题我改变了

$(document).ready

$(window).load

解决。感谢@sdespont

相关问题