注意:这与pdf viewer适合页面功能相同
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/
提前致谢。
答案 0 :(得分:1)
与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。