【问题标题】:Set height of Img via JavaScript通过 JavaScript 设置 Img 的高度
【发布时间】:2019-01-05 12:07:50
【问题描述】:

我的代码目前遇到问题。我正在尝试通过 JavaScript 设置图像的高度,以检查其小于 600 像素。我尝试了很多替代一般“this.height = 600”的方法,但没有一个成功。我真的希望有人能帮我解决这个问题。

<div id="cursedframe">  
  <img src="" id="cursedimg">
</div>

<script>

function setImage() {
    var img = new Image();
    var images = [
        "bean.jpg",
        "xxx-edit-parallax/Images/xxx-5.jpg"
    ];

    var chosen = images[Math.floor(Math.random() * images.length)];

    img.onload = function(){

    if (this.height > 600) {
            console.log("more than");
            this.height = 600;
            console.log(img.height);
        } else {
            console.log("less than");
            this.height = "auto";
            console.log(this.height);
        }
    };

    img.src = chosen.toString();
    document.getElementById("cursedimg").src = img.src;
}   


</script>

它成功通过了“if”,但从未真正设置高度。

编辑:当时不知道 max-heightmax-width 的 CSS 属性。 Lain 引起了我的注意。谢谢

【问题讨论】:

  • 你不能在 css 中将 max-height 设置为 600px 吗?似乎和你在这里所做的差不多。
  • 哇。那是一回事?啊,救主!我认为可以肯定地说我对 CSS 无感
  • 顺便说一句,您永远不会将任何加载事件分配给document.getElementById("cursedimg")。仅针对名为img 的非DOM 图像,它对您实际显示的图像没有影响。您需要添加document.getElementById("cursedimg").style.height = img.height + 'px';

标签: javascript height


【解决方案1】:

使用css属性max-height会容易得多。

只是为了显示 javascript 方法的实际缺陷:您必须将高度传递给实际图像。目前,您只需将其设置为img 对象,而从未设置为显示的图像&lt;img src="" id="cursedimg"&gt;

var img = new Image();
var images = ['https://logosmarken.com/wp-content/uploads/2018/05/Google-Logo.png'];
var maxHeight = 200; //REM: For my test image

img.onload = function(){
    if (this.height > maxHeight) {
        console.log("more than");
        this.height = maxHeight;
        console.log(img.height);
    } else {
        console.log("less than");
        this.height = "auto";
        console.log(this.height);
    };
    
    //REM: Here you need to assign the src along with the height
    document.getElementById("cursedimg").src = this.src;
    document.getElementById("cursedimg").style.height = this.height + 'px';
};

//REM: No need for toString() - it already is.
img.src = images[Math.floor(Math.random() * images.length)];
<div id="cursedframe">  
  <img src="" id="cursedimg">
</div>

更简单的方法是根本不创建新对象并按原样分配它: var img = document.getElementById("cursedimg");

【讨论】:

    【解决方案2】:

    通过运行以下代码,您将唯一的 src 属性分配给 img 元素

    img.src = chosen.toString();
    document.getElementById("cursedimg").src = img.src;
    

    如果要使用javascript设置图像元素的高度和src, 您可以执行以下操作:

    var image = document.getElementById("cursedimg");
    if ( image.height > 600 ){
         image.height = 600;
    }
    else{
         image.style.height = "auto";     // since 'auto' is a styling value
    }
    image.src = chosen.toString();
    

    【讨论】:

      猜你喜欢
      • 2013-08-10
      • 2020-03-23
      • 1970-01-01
      • 2013-11-24
      • 1970-01-01
      • 2012-06-18
      • 2019-02-03
      • 2021-11-24
      • 2019-09-12
      相关资源
      最近更新 更多