首页 > 解决方案 > 如何提取我的函数 JavaScript 的返回值

问题描述

我使用此函数来获取照片的宽度/高度比率,以分配纵向或横向的自动值:

    var newimage = new Image();
    newimage.src = ImageDir; //Directory of my image
    newimage.onload = function ratio()
{
    var width = this.naturalWidth;
    var height = this.naturalHeight;
    var divi = (width/height);
    return divi.value;
}
alert(divi)

将返回正确的值,但我想在公司中使用此代码:

if (divi > 1) {
        node.getElementById("myImage"+"-"+nump).dataset.size = ("1600x1200");
    } else {
        node.getElementById("myImage"+"-"+nump).dataset.size = ("1200x1600");
}

我试过这样的东西:

var newimage = new Image();
    newimage.src = ImageDir; //Directory of my image
    newimage.onload = function ratio()
{
    var width = this.naturalWidth;
    var height = this.naturalHeight;
    var divi = (width/height);
    if (divi > 1) {
        node.getElementById("myImage"+"-"+nump).dataset.size = ("1600x1200"); //nump is the number of repetitions the While loop as been in (for increments)
    } else {
        node.getElementById("myImage"+"-"+nump).dataset.size = ("1200x1600");
}
}

但是 if 和 else 的值不会输出……如果我把它们放在第一个函数之外,它们就会输出。这都是在一个 While 循环中,所以 divi 变量每次都会改变。

有人可以帮我获得 If 条件的 Divi 值吗?谢谢!

标签: javascript

解决方案


推荐阅读