【问题标题】:Change image size with JavaScript使用 JavaScript 更改图像大小
【发布时间】:2010-11-20 19:29:58
【问题描述】:

我正在尝试使用 JavaScript 更改图像的大小。 jS 文件与 HTML 页面是分开的。

我想在 JS 文件中设置图片的高度和宽度。有什么好的方法吗?

【问题讨论】:

    标签: javascript image


    【解决方案1】:

    一旦你引用了你的图片,你可以像这样设置它的高度和宽度:

    var yourImg = document.getElementById('yourImgId');
    if(yourImg && yourImg.style) {
        yourImg.style.height = '100px';
        yourImg.style.width = '200px';
    }
    

    在 html 中,它看起来像这样:

    <img src="src/to/your/img.jpg" id="yourImgId" alt="alt tags are key!"/>
    

    【讨论】:

    • 您必须确保在页面加载完成后执行 javascript。您可以通过将其置于 onload 事件中来做到这一点,或者将脚本放在页面底部,就在结束 body 标记之前。
    • 有什么办法可以在样式改变后改变实际高度yourImage.height = 100而不裁剪图像?
    • 当然,如果你想稍后只调整一个维度,并保持图像的纵横比,你可以使用auto作为你没有明确设置的值(例如yourImg.style.height = '500px'yourImg.style.width = 'auto')。这是我整理的一个简单示例:codepen.io/patheard/pen/aEwfn
    • @Pat 所以我们可以把它放在 onload 事件中;)
    • @Pat 在我看来不需要(如果条件)浏览器有 2 个选项(支持 Javascript/不支持)我认为没有选项 3
    【解决方案2】:

    您可以像这样更改实际的宽度/高度属性:

    var theImg = document.getElementById('theImgId');
    theImg.height = 150;
    theImg.width = 150;
    

    【讨论】:

    • 如果图像的宽度和高度是通过 CSS 设置的,似乎不起作用
    【解决方案3】:

    如果要在加载后调整图像大小,可以附加到&lt;img&gt; 标记的onload 事件。请注意,并非所有浏览器都支持它(Microsoft's reference 声称它是 HTML 4.0 规范的一部分,但HTML 4.0 spec 没有列出onload 事件&lt;img&gt;)。

    以下代码经过测试并在以下环境中运行:IE 6、7 和 8、Firefox 2、3 和 3.5、Opera 9 和 10、Safari 3 和 4 以及 Google Chrome:

    <img src="yourImage.jpg" border="0" height="real_height" width="real_width"
        onload="resizeImg(this, 200, 100);">
    
    <script type="text/javascript">
    function resizeImg(img, height, width) {
        img.height = height;
        img.width = width;
    }
    </script>
    

    【讨论】:

      【解决方案4】:

      更改图像很容易,但是更改后如何将其更改回原始大小?您可以尝试将文档中的所有图像更改回原始大小:

      var i,L=document.images.length; for(i=0;i

      【讨论】:

        【解决方案5】:

        you can see the result here 在这些简单的代码块中,您可以更改图像的大小,并在鼠标进入图像时使其变大,当鼠标离开时它会恢复到原来的大小。

        html:

        <div>
        <img  onmouseover="fifo()" onmouseleave="fifo()" src="your_image"   
               width="10%"  id="f" >
        </div>
        

        js文件:

        var b=0;
        function fifo() {
               if(b==0){
                    document.getElementById("f").width = "300";
                   b=1;
                  }
               else
                  {
                 document.getElementById("f").width = "100";
                  b=0;
                }
           }
        

        【讨论】:

          【解决方案6】:

          直接操作

          图片的HTML标签声明:

          <img id="my-img" src="src/to/your/image.jpg" width="1280px" height="720px" />
          <!-- OR -->
          <img id="my-img" src="src/to/your/image.jpg" style="width: 1280px; height: 720px;" />
          

          通过直接访问对象图像处理html标签:

          const myImg = document.getElementById("my-img");
          
          // Set a new width and height
          myImg.style.width = "800px";
          myImg.style.height = "450px";
          // Or set a new width and height by attribute
          // This option is not advisable because the attribute has a 
          // low priority over the style property.
          myImg.setAttribute("width", 800);
          myImg.setAttribute("height", 450);
          

          操作函数

          使用下面的updateImageSizeWithWidthupdateImageSizeWithHeight 方法,您可以增加或减少任何图像,而无需明确指定确切的宽度和高度,您只需要这两个值中的一个值即可更新图像大小。

          /**
           * Update image size using width
           *
           * param {HTMLImageElement} img
           * param {number} newWidth
           */function updateImageSizeWithWidth(img, newWidth) {
            // Getting the width and height of the current image 
            const oldWidth =  Number.parseFloat(getComputedStyle(img).width || img.getAttribute("width"));
            const oldHeight = Number.parseFloat(getComputedStyle(img).height || img.getAttribute("height"));
            // Getting proportional height with new width
            const newHeight = (newWidth * oldHeight)/oldWidth;
            // Setting dimensions in the image
            img.style.width = `${newWidth}px`;
            img.style.height = `${newHeight}px`;
          }
          
          /**
           * Update image size using height
           *
           * param {HTMLImageElement} img
           * param {number} newHeight
           */
          function updateImageSizeWithHeight(img, newHeight) {
            // Getting the width and height of the current image 
            const oldWidth =  Number.parseFloat(getComputedStyle(img).width || img.getAttribute("width"));
            const oldHeight = Number.parseFloat(getComputedStyle(img).height || img.getAttribute("height"));
            // Getting proportional height with new width
            const newWidth = (newHeight * oldWidth)/oldHeight;
            // Setting dimensions in the image
            img.style.width = `${newWidth}px`;
            img.style.height = `${newHeight}px`;
          }
          
          updateImageSizeWithWidth(myImg, 800);
          // Or
          updateImageSizeWithHeight(myImg, 450);
          

          【讨论】:

            【解决方案7】:
            //  This one has print statement so you can see the result at every stage if     you would like.  They are not needed
            
            function crop(image, width, height)
            {
                image.width = width;
                image.height = height;
                //print ("in function", image, image.getWidth(), image.getHeight());
                return image;
            }
            
            var image = new SimpleImage("name of your image here");
            //print ("original", image, image.getWidth(), image.getHeight());
            //crop(image,200,300);
            print ("final", image, image.getWidth(), image.getHeight());
            

            【讨论】:

            • 试着在你的答案中描述你在做什么,而不是仅仅粘贴裸露的源代码。如果你这样做,它几乎总是能帮助提问者更多。
            【解决方案8】:

            你可以这样做:

            • .html 文件:
            <img src="src/to/your/img.jpg" id="yourImgId"/>
            
            • .js 文件:
            document.getElementById("yourImgId").style.height = "heightpx";
            

            你可以对宽度做同样的事情。

            【讨论】:

              猜你喜欢
              • 2011-03-11
              • 1970-01-01
              • 2017-04-19
              • 1970-01-01
              • 2012-08-04
              • 2018-12-25
              • 2010-11-13
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多