我目前遇到我的代码问题。我试图通过 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”,但从未真正设置过高度。
编辑:在不知道的CSS属性max-height
,并max-width
在当时。Lain 引起了我的注意。谢谢
使用 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");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句