如何使用 JavaScript 设置一个元素的边距等于另一个元素的高度? [英] How to set margin of one element equal to height of other element using JavaScript?

查看:22
本文介绍了如何使用 JavaScript 设置一个元素的边距等于另一个元素的高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用javascript将div2margin-top设置为等于div1的高度(无论高度是多少)并且比 div2 可见.

I want to set the margin-top of div2 equal to height of div1 using javascript (no matter how much the height is) and than div2 would be visible.

.div1 {
  width: 50%;
  height: 100px;
  position: absolute;
  top: 0;
  left: 0;
  background-color: red;
}

.div2 {
  width: 50%;
  height: 100px;
  background-color: blue;
}

<div class="div1"></div>
<div class="div2"></div>

推荐答案

也许是这样的:

var div1Height = document.getElementsByClassName("div1")[0].style.height;
document.getElementsByClassName("div2")[0].style.margin = div1Height;

我发现 MDN 很有帮助(提示:尝试花点时间学习语言).

I have found MDN helpful (hint: try taking the time to learn the language).

这篇关于如何使用 JavaScript 设置一个元素的边距等于另一个元素的高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆