gpt4 book ai didi

javascript - 在父 div 中安装子 div

转载 作者:行者123 更新时间:2023-11-28 18:01:52 25 4
gpt4 key购买 nike

像往常一样,我有一个父子 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);
});
});

fiddle - 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 .

关于javascript - 在父 div 中安装子 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20281652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com