繁体   English   中英

javascript根据元素的高度更改高度

[英]javascript change height based on element's height

我需要将元素的高度设置为等于div的高度,该高度根据其内部的元素而变化

我做了这个JavaScript代码,但没有用。

怎么了

jsfiddle

HTML

<div id="a" onclick="changeHeight();">
</div>
<div id="button">
</div>

JAVASCRIPT

function changeHeight() {
var divHeight = $("#a").height();
document.getElementById('button').style.height = divHeight;
}

CSS

#a{width:300px;height:100px;background-color:black;}
#button{width:300px;background-color:green;}

'px'连接(单位)

 function changeHeight() { var divHeight = $("#a").height(); document.getElementById('button').style.height = divHeight + 'px'; } 
 #a { width: 300px; height: 100px; background-color: black; } #button { width: 300px; background-color: green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div id="a" onclick="changeHeight();"></div> <div id="button"></div> 

为什么要混合使用jQuery和Vanilla Js? 我完全用jQuery编写了它,看起来好像正在工作:

 function changeHeight() { var divHeight = $("#a").height(); $('#button').height(divHeight); } 
 #a{width:300px;height:100px;background-color:black;} #button{width:300px;background-color:green;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="a" onclick="changeHeight();"> </div> <div id="button"> </div> 

更新的小提琴: https : //jsfiddle.net/sne40vh1/3/

主要问题是您试图设置#button的高度而没有测量单位(jQuery的.height方法仅返回一个值,没有测量值),因此当您尝试在原始JavaScript中设置样式时,需要使用度量单位,这是失败的(因此,在这种情况下,它需要'300px',但您只是给它了'300'。

我在这里将其更改为具有全局功能(不推荐使用,我只是这样做是为了使小提琴正常工作),并更改了设置#button的高度的#button以匹配获取高度的方式#a

HTML:

<div id="a" onclick="changeHeight()"></div>
<div id="button"></div>

CSS:

#a{width:300px;height:100px;background-color:black;}
#button{width:300px;background-color:green;}

JS:

changeHeight = function() {
  var divHeight = $("#a").height();
  $('#button').height(divHeight);
}

随时将我所做的与您所做的事情进行比较,以更好地查看我的更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM