【问题标题】:How to use JavaScript to scale an image to fit如何使用 JavaScript 缩放图像以适应
【发布时间】:2014-11-04 09:07:51
【问题描述】:

我有一个 67x67 像素的图像,我想缩小到 45x45 以适应锚点,但我不知道如何调整它。我的 HTML 是:

<a class="CompareProfilePic" id="CompareProfilePic1" href="#">
   <span id="CompareProfilePicActionBtn1" class="autocenter">
   </span>
</a>

我的 CSS 是:

a.CompareProfilePic {
   height: 45px;
   width: 45px;
   border-radius: 50%;
   float: left;
   margin-right: 10px;
   cursor: default !important;
}

而我的 JS 是:

document.getElementById('CompareProfilePic1').style.cssText = 'background-image: url(img/pic1.jpg)';

我的所有搜索都导致更改了图片的大小,但这需要保持 45x45。有关如何将图像缩放到该尺寸的任何建议?

感谢任何提示或指示。

【问题讨论】:

    标签: javascript html css image scale


    【解决方案1】:
     $(this).css('width','px');
     $(this).css('height','auto');
    

    stackoverflow 上的这个帖子回答了

    javascript Image Resize

    【讨论】:

    • 这个答案有什么问题?他问js,不是吗?
    【解决方案2】:

    不使用 JS,只使用带有background-size 的 CSS 怎么样?

    a.CompareProfilePic {
        height: 45px;
        width: 45px;
        border-radius: 50%;
        float: left;
        margin-right: 10px;
        cursor: default !important;
        background-image: url(img/pic1.jpg);
        background-size: 45px 45px; /*<----*/
    }
    

    【讨论】:

      【解决方案3】:

      看看 here:

      我用过

      document.getElementById('CompareProfilePic1').style.backgroundSize = "45px 45px";
      

      【讨论】:

      • 啊,太完美了!不敢相信这很容易,但我在其他任何地方都找不到。谢谢!
      猜你喜欢
      • 2023-03-19
      • 2015-11-18
      • 1970-01-01
      • 1970-01-01
      • 2019-03-12
      • 2013-10-25
      • 2019-04-08
      • 1970-01-01
      • 2015-02-19
      相关资源
      最近更新 更多