Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

javascript - Bug while trying to get the size of a div

I'm using Vue. I have a div which look like this:

<div :style="'width:' + imageSize.width + 'px; height:' + imageSize.height + 'px'" id="image-container"></div>

The dimension are stored in my data like this:

data() {
return {
  ...
  imageSize: {
    width: 500,
    height: 500
  }
  ...
}

Also I have two buttons to zoom in and out the div:

<v-btn rounded color="white" class="ma-2" @click="zoom('+')">
   <v-icon>mdi-magnify-plus-outline</v-icon>
</v-btn>
<v-btn rounded color="white" class="ma-2" @click="zoom('-')">
  <v-icon>mdi-magnify-minus-outline</v-icon>
</v-btn>

The zoom's function look like this:

zoom(type) {
  if(type == '+') {
     this.imageSize.height += 100;
     this.imageSize.width += 100;
     console.log('Zoom in clicked!')
  } else {
     this.imageSize.height -= 100;
     this.imageSize.width -= 100;
     console.log('Zoom out clicked!')
  }
  const { offsetWidth, offsetHeight } = document.getElementById("image-container");
  console.log(offsetWidth);
  console.log(offsetHeight);
},

When I click the button to zoom in the div everything works and the size of the div increases by 100px per side. But when I get the size of the div (which I need to save in the data) the size stays the same. Also I noticed that if I click again I get the previous zoom size. Here is the screenshot of the console: Screenshot of the console

When i get 500 i should get 600 and so on. Thanks in advance!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
setTimeout(() => {
    const { offsetWidth, offsetHeight } = document.getElementById("image-container");
  console.log(offsetWidth);
  console.log(offsetHeight);
}, 100)

try this after the if else block.

This happend to me 2 days ago while animating with gsap. My guess is, by the time the image.height or image.width changes the other statements runs before it , ie it took time to change it.

I tried this and in my case it worked.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...