【问题标题】:Copy divs height and apply it to an other div with Javascript复制 div 高度并使用 Javascript 将其应用到另一个 div
【发布时间】:2021-11-20 08:40:49
【问题描述】:
<div class="thisOne">
</div>

<div class="thisHeight">
</div>

我想复制 thisHeight div 的高度并将其应用到 thisOne div,因此这两个 div 将始终具有相同的高度。

【问题讨论】:

  • 何时应用此高度?在哪个活动上?

标签: javascript html css web


【解决方案1】:
  1. 找到那个元素
  2. 获取它的偏移高度
  3. 找到另一个元素
  4. 设置高度
const elem = document.querySelector(`.thisHeight`);
const elemHeight = elem.offsetHeight;
const secondElem = document.querySelector(`.thisOne `);
secondElem.style.height = elemHeight;

【讨论】:

    【解决方案2】:

    您可以将多个 CSS 应用于单个 div,如下所示(通过在其间使用单个空格分隔):

    <div class="thisOne thisHeight">
    </div>
    

    这将复制 thisHeight 中的所有样式,因此如果您只想使用高度,则应将其分离为单独的样式。

    <style>
    thisOne {... }
    
    thisOneHeight {... }
    
    myHeight {
         height : 100px;
              }
    </style>
    
    <body>
    
    <div class="thisOne myHeight"></div>
    
    <div class="thisHeight myHeight"></div>
    
    </body>
    

    【讨论】:

      【解决方案3】:

      您可以在 javascript 中执行以下操作:

       const height = document.getElementsByClassName('thisHeight')[0].offsetHeight;
       document.getElementsByClassName('thisOne')[0].style.height = `${height}px`;
      

      我不知道您的最终目标是什么,但我建议您看看 flexbox 以获得仅 CSS 的解决方案。

      信息可以在这里找到:https://css-tricks.com/snippets/css/a-guide-to-flexbox/

      【讨论】:

        【解决方案4】:

        您可能正在寻找 .getBoundingClientRect() 函数来计算元素的高度和宽度

        var thisHeight = document.querySelector(".thisHeight"),
            thisOne = document.querySelector(".thisOne")
            
        function copyHeight(from,to){
            to.style.height = from.getBoundingClientRect().height + "px"
        }
        
        copyHeight(thisHeight,thisOne)
        .border {border:1px solid gray;}
        <div class="thisOne border">
            copied height
        </div>
        
        <div class="thisHeight border">
            Lorem ipsum dolor sit amet consectetur adipisicing elit. Nulla maxime pariatur quia libero vitae blanditiis velit temporibus? Esse modi perspiciatis consectetur eius nihil magnam, quaerat, dignissimos nisi unde quas quod!
        </div>

        【讨论】:

          猜你喜欢
          • 2014-05-22
          • 2012-07-17
          • 1970-01-01
          • 1970-01-01
          • 2018-08-27
          • 1970-01-01
          • 1970-01-01
          • 2021-04-12
          相关资源
          最近更新 更多