The difference between javascript width and height assignment in ie and Chrome/Firefox

Lionsure 2020-06-28 Original by the website

When writing javascript code, only assign the value to the height or width of an object, you will find that it is valid in Internet Explorer, but it is invalid in browsers such as Chrome and Firefox that comply with the W3C standard, you must add "px". Examples of specific situations.

 

Example 1: Height and width of image cannot exceed a specified value

<div id="test1">
              <img src="/images/logo.gif" alt="Lionsure" />
              <img src="/images/ads.gif" alt="Page can not open" />
       </div>

<script type="text/javascript">
       function SetHeightWidthOfImg(height, width){
              var obj = document.getElementById("test1");
              var imgs = obj.getElementsByTagName("img");

       for(var i = 0;i < imgs.length;i++){
                     //imgs[i].height = height; //Valid in Ie, invalid in Chrome and Firefox
                     imgs[i].height = height + 'px'; //Valid in Ie, Chrome and Firefox

              //imgs[i].width = width;//Valid in Ie, invalid in Chrome and Firefox
                     imgs[i].width = width + 'px';//Valid in Ie, Chrome and Firefox
              }

}
       SetHeightWidthOfImg(700, 600);
       </script>

Note: In the above example, scaling is not achieved based on the incoming values. If you want to scale proportionally, please see the article "Perfect and Efficient Resolution of IE6 Image Scale Down", which has detailed implementations.

 

Example 2: Determine the width of iframe based on the screen

<div id="leftMenu">
              <ul id="test1">
                     <li>Page can not open in Ie</li>
                     <li>Page can not open in Chrome</li>
                     <li>Page can not open in Firefox</li>
              </ul>
       </div>
       <div id="right">
              <iframe id="ifr" onload="this.height=ifr.document.body.scrollHeight" width="100%" scrolling="no" frameborder="0" marginwidth="0" marginheight="0" src="index.htm"></iframe>
       </div>

<script type="text/javascript">
       function setWidth(width){
              //document.getElementById("right").style.width = document.body.scrollWidth - width; //Valid in Ie, invalid in Chrome and Firefox
              document.getElementById("right").style.width = document.body.scrollWidth - width + 'px';//Valid in Ie, Chrome and Firefox
       }
       setWidth(200);
       </script>

In addition to the examples given above, all those involved in the assignment of object height and width must not have "px", especially after calculating a few values, don't forget to add "px" to the back.