我有一个父div,响应宽度和固定高度,里面有一些图像.在运行时,我需要一个Jquery函数来计算div的宽度和高度,并将宽度(px)和高度(px)参数应用于图像.即我现在的代码是
<div id="slider-wrapper" class="someclass">
<img src="/image1.jpg" alt="" />
<img src="/image2.jpg" alt="" />
<img src="/image3.jpg" alt="" />
</div>
Run Code Online (Sandbox Code Playgroud)
我需要的生成代码
<div id="slider-wrapper" class="someclass">
<img src="/image1.jpg" height="300px" width="total-div-width(px)" alt="" />
<img src="/image2.jpg" height="300px" width="total-div-width(px)" alt="" />
<img src="/image3.jpg" height="300px" width="total-div-width(px)" alt="" />
</div>
Run Code Online (Sandbox Code Playgroud)
谢谢你的期待
使用jQuery,你可以使用.height(),.innerHeight()或.outerHeight().
不同之处是:
height() 只返回元素的高度,没有边框,没有边距,也没有填充innerHeight() 返回元素高度和填充outerHeight() 返回元素高度,填充和边框outerHeight(true) 返回元素高度,填充,边框和边距我在这里有更多细节,包括使用jsFiddle的输出示例.
对于宽度,您可以使用width(),innerWidth()或outerWidth().
同样的逻辑适用于高度.
所有值都以像素为单位.
要获得高度/宽度,您可以使用它类似于:
// The below is an example, you need to add your element references as required.
// Use height(), innerHeight() or outerHeight() as needed.
var newHeight = $("#slider-wrapper").height();
// Use width(), innerWidth() or outerWidth() as needed.
var newWidth = $("#slider-wrapper").width();
Run Code Online (Sandbox Code Playgroud)
要设置高度/宽度,您可以使用它类似于:
// The below is an example, you need to add your element references as required.
var newHeight = $("#slider-wrapper img").height(newHeight);
var newWidth = $("#slider-wrapper img").width(newWidth);
Run Code Online (Sandbox Code Playgroud)