简体   繁体   中英

Getting width from hidden image with JavaScript

I have in my HTML an image (id=”stone”) which I hide. From this image I make later several copies (id=”stone_xxx) in JS with cloneNode, put them in the DOM and remove the hidden-class. Everything works all right. I need the width initially at program start (before I make the first copy) so I take it from the hidden image (id=”stone”). But I always get the naturalHeight (90px) and not the actual height (45px).
I even tried it in the console to exclude that perhaps CSS is executed after JS but this didn`t change anything, so I had to use window.onload like in Get image width height javascript .

 let stone = document.getElementById( "stone" ); let newStone = stone.cloneNode( false ); newStone.classList.remove( 'hidden' ); let i = 1; newStone.id = "stone_" + i; let el = document.getElementById( 'position_' + i); el.prepend(newStone); console.log(stone.naturalWidth); // => 272 console.log(stone.width); // => 272 Should be: 45
 .hidden { display: none;}.stone { width: 45px;}
 <img id="stone" class="stone hidden" src=https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png /> <div id="position_1"></div>

I solved it: The browser doesn't calculate the new dimensions of stone because of display none so the value of width isn´t recalculated. If I remove the class hidden everything is ok. So I have 2 possibilities:
• Starting without class hidden and setting it afterwards.
• Get the width of one of the clones stones_xxx:

let newStone = document.getElementById( "stone_xxx" );
let width = newStone.width;
console.log(width);   // => 45

Try this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <img id="image" src="http://www.fillmurray.com/200/200" alt="image" />

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
      const width = $('#image').width();

      console.log(width); // 200
    </script>
  </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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