[英]Fitting child div inside parent div
和往常一样,我有一个父母和孩子的div。 子div的尺寸不固定。 在点击事件中,我想更改子div的尺寸以使其完全适合父div。
注意:这与pdf查看器适合页面功能相同
HTML:
<a href="javascript:void(0)">Click</a>
<div id="parent">
<div id="child4" class="child"></div>
<!-- Please check by commenting childs one by one
<div id="child2" class="child"></div>
<div id="child3" class="child"></div>
<div id="child4" class="child"></div>
-->
</div>
CSS:
#parent {width:200px; height:100px; margin:100px auto; border:1px solid #000; overflow:auto}
.child {margin:0; border:1px solid #000; background-color:maroon; opacity:0.5}
#child1 {width:100px; height:50px}
#child2 {width:400px; height:100px}
#child3 {width:100px; height:500px}
#child4 {width:400px; height:500px}
JQuery的:
$(function(){
// Fit block
$("a").click(function(){
//I want logic here to fit $(".child") div perfectly
//inside $("#parent") div. After changes dimensions
//of child should be in proportion to its original width/height.
//if height is more
//then it should get parents height and if width is more
//than it should get parents width but there should be no
//vertical or horizontal scroll
$(".child").height($("#parent").height() - 20);
});
});
小提琴-http: //jsfiddle.net/LaT3E/4/
提前致谢。
类似于CSS background-size:contain;
作品?
解决方法如下:
$(function(){
var $child = $('.child'),
h = $child.height(),
w = $child.width(),
bw = $child.css('border-width').replace('px',''),
parH = $('#parent').height(),
parW = $('#parent').width(),
car = w / h,
par = parW / parH,
newH,
newW;
$('a').click(function(){
if(car > par){
newW = parW;
newH = h / w * newW;
}else{
newH = parH;
newW = w / h * newH;
}
$child.width(newW-bw*2);
$child.height(newH-bw*2);
console.log(w+'X'+h+' to '+newW+'X'+newH)
});
});
检查此jsfiddle 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.