通过JavaScript设置Img的高度

时间:2018-07-11 14:12:20

标签: javascript height

我当前遇到代码问题。我正在尝试通过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属性。引起了莱恩的注意。谢谢

2 个答案:

答案 0 :(得分:1)

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

仅显示javascript中方法的实际缺陷:您必须将高度传递给实际图像。当前,您仅将其设置为img对象,而从未设置为显示的图像<img src="" id="cursedimg">

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");

答案 1 :(得分:0)

通过运行以下代码,您将仅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();