1

私はブラウザのウィンドウ幅の結果を取得しようとしていて、数学と条件の結果を変数に入れようとしていました。これはコードです

var MyWidth = 1900;
var MyHeight = 900;
var height = $(window).height();
var width = $(window).width();

var AutoW = function () {
    if ( (MyWidth / width).toFixed(2) > 0.95 )
          return 1;
    if ( (MyWidth / width).toFixed(2) < 1.05 )
          return 1;
    else return (MyWidth / width).toFixed(2);
     };


alert(AutoW);

問題は、変数に割り当てられた関数の正しい構文または構造がわからないことです

これをコーディングする正しい方法は何ですか?

4

4 に答える 4

2

alert(AutoW());

AutoW()変数に割り当てられた関数の値を返します。

フィドル: http://jsfiddle.net/V2esf/

于 2013-05-13T07:02:59.677 に答える
1
var AutoW = function () {
    // don't calculate ratio 3 times! Calculate it once
    var ratio = (MyWidth / width).toFixed(2);
    if (ratio > 0.95)
          return 1;
    if (ratio < 1.05)
          return 1;
    else return ratio;
};


// alert(AutoW); - this was a problem, AutoW is a function, not a variable
// so, you should call it
alert(AutoW());
于 2013-05-13T07:04:57.910 に答える
1
<script>
    var MyWidth = 1900;
    var MyHeight = 900;
    var height = $(window).height();
    var width = $(window).width();

    var AutoW = function () {
        if ((MyWidth / width).toFixed(2) > 0.95)
            return 1;
        if ((MyWidth / width).toFixed(2) < 1.05)
            return 1;
        else return (MyWidth / width).toFixed(2);
    };

    var val = AutoW();
    alert(val)
</script>
于 2013-05-13T07:05:34.013 に答える
1

この方法を試してください:

(function(){

var MyWidth = 1900,
MyHeight = 900,
height = $(window).height(),
width = $(window).width(),
result;

var AutoW = function () {
    var rel = (MyWidth / width).toFixed(2);
    return ( ( rel > 0.95 ) && ( rel < 1.05 )) ? 1 : rel;
};

result = AutoW();

alert(result);

})();

ただし、作成した関数は常に 1 を返すことを覚えておいてください。そのため、(&&) 条件に変更してフィルターにしました。

関数のアラートを作成すると、関数全体が返されます。関数「()」のキャストを変数に割り当てる必要があるため、戻り値が変数に割り当てられます。

var result = f_name();

また、グローバル変数を使用しないようにして、すべてを関数にラップすることを忘れないでください。

if の後に {} を置き、"(MyWidth / width).toFixed(2)" を rel.

if >> (条件) の代わりに使用したシンタックス ? (一致する場合は返す) : (そうでない場合は返す);

于 2013-05-13T07:13:43.410 に答える