css 如何检测Vue3中div1的实时高度变化,得到div1的高度减去div2的12px?

cbwuti44  于 2023-06-25  发布在  其他
关注(0)|答案(2)|浏览(229)

我有个问题解决不了如何在Vue 3中检测div 1的实时高度变化,并获得div 1减去div 2的12 px的高度?
如果div 1包含多行文本,并且其高度从100 px扩展到150 px,我如何获得div 2的150 px-12 px = 138 px的值,并将138 px的高度分配给div 2?
enter image description here
我为造成的任何混乱道歉。英语不是我的主要语言。如果你有任何问题,请告诉我。
最好的问候。
我可以捕捉到初始高度,但当它改变高度时,我无法实时捕捉到它。

7uzetpgm

7uzetpgm1#

<script>
   import { ref } from 'vue'

   const input = ref(null);
   const second = ref(null);

   var height = 0; // to store first div height
   var height2 = 0; // to store second div height
   watchEffect(() => {
       const observer = new ResizeObserver(() => {
          height = (input.current || {}).clientHeight || 0;
          if (height > 0) height2 = height - 12;
       });
   });

</script>

<template>
  <div1 ref = "input" />
  <div2 ref = "second" />
</template>

这里有一个解决问题的方法。ResizeObserver计算div内的文本更改时的高度。监听此事件watchEffect用于跟踪它。我希望这对你有用。我不工作的vue,但给了它一个尝试类似的React。所以,如果有任何错误,请道歉。

j1dl9f46

j1dl9f462#

我没看到照片!!
使用MutationObserver

<script setup>
import {
    ref,
    watch,
  onBeforeUnmount
} from 'vue'

const heightDiv1 = ref(0)
const mutationHandler = mutationList => {
    for (let mutation of mutationList) {
        if (mutation.type === "attributes") {
            const {
                height
            } = mutation.target.getBoundingClientRect();

            heightDiv1.value = height
        }
    }
};
const mo = new MutationObserver(mutationHandler);
onBeforeUnmount(() => mo.disconnect())

const div1Ref = ref()
watch(div1Ref, (div1Ref) => {
    if (!div1Ref) return
    heightDiv1.value = div1Ref.getBoundingClientRect().height

    mo.observe(div1Ref, {
        attributes: true,
        childList: true,
        subtree: true
    });
})
</script>

<template>
  <div ref="div1Ref" class="div1">
    div 1
    <textarea />
  </div>
  Height div 1: {{heightDiv1}}
  <div :style="{ height: heightDiv1 - 12 + 'px'}" class="div2">
    div 2
  </div>
</template>

<style scoped>
  .div1 {
    background: red
  }
  .div2 {
    background: blue
  }
</style>

预览:https://play.vuejs.org/#eNp1U8uO2zAM/BXWlzjo1mlydOMA3fawhxYFFuhNFz/oRKgtGTKd3YXhfy/1sOMU20MSiRwNOUNmjL52XXIdMEqjY18a2RH0SEN3Ekq2nTYEo1CCDNYP9vclp/LCJwCtHrHWBn+rVg+KhJqgNrqFDZNtGKpKrXqCC8rzhb7L6x4yYJb483ZOtQPlJLV6ylXVoOH8HPkhOZ2dfGkuAnGDNzzo+g659ThBsoZ4TiT01iFkWQYiyomMLAbCXkQLWJDvYrkK8r3O92nVUEK5OSMl/HlktZVU52+NREXPWFK8/WL1rjms3uSaNwO3ECzwgMn+8NfET4ILmiEKX+BnqPWr6NFc0SxSgj+2yj+mx/HW2tTqpJI90ynXDRs8k1fcxzPWwXpOuPnFIfwA88nROCeshx+WqOFVME7bO7oC6n+mJItufs4taq/rVjw4f5tOCmQGdHvG07nIprLjvYv2Q8G7iD7mvLS2TKzsuPPry4vLF8K2a3JCvgEcuaQ1IBNRKC4iKJu870NERA4HVhLs/ZEpXnnqmMPOk+w46U5PTpfHpjCON2smnmwol/b01iDzj2H+6fqv8An2B/gIm+51M933crjr5bCufNytVPHVVQCee4eVe8NbwNxsq31e5OWfs7FzSVl7ZYOuOws6vAcqeKoBxV5a7lM0/QX5snT1

相关问题