offset(fn)


version 1.4 以降

解説

マッチした最初の要素の、ドキュメントの左上からの相対位置を設定します。

引数

  • fn
    Function:position: relative に対する、top(上からの位置) と left(左からの位置)をプロパティに持つオブジェクトを返す関数。
    このコールバック関数には、要素のインデックスと、現在の offset の内容が渡されます。
    obj.offset(function(i, coordinates) {
        // 要素のインデックス
        index;
        // 現在の offset の内容
        coordinates; 
        // 現在の offset().top の内容
        coordinates.top; 
        // 現在の offset().left の内容
        coordinates.left; 
    
        // 新しい offset の値を返す(position: relative に対する位置)
        return {top: boo, left: foo};
    });
    

    もしくは、top(上からの位置)、left(左からの位置)、using プロパティにコールバック関数を設定したオブジェクトを返す関数。
    このコールバック関数には、offset の計算結果が渡されます。
    usingプロパティにコールバック関数を設定したオブジェクトを返した場合は、現在の offset 値は変更されません。
    もし、変更したい場合は、using 関数の中で処理します。
    obj.offset(function(i, coordinates) {
        return {
            top:  10,    // offset の計算に使用され、適用されない
            left: 10,    // offset の計算に使用され、適用されない
            using: function(calcOffset) {
                // offset の計算結果(position: relative に対する位置)
                calcOffset;
    
                // 適用する場合
                $(this).css(calcOffset);
            }
        };
    });
    

戻り値

  • jQuery: jQueryオブジェクト

関連


例1:.box をクリックすると、10 ピクセルづつ移動します。
10回毎に方向が変わります。

$(".box").click(function() {
    var box = $(this);

    box.offset(function(i, coordinates) {
        var count     = box.data("count") || 0;
        var direction = box.data("direction") || 1;

        direction = count == 10 ? -1 : count == 0 ? 1 : direction;
        count = count + direction;

        box.data("count",     count);
        box.data("direction", direction);

        return {
            top:  coordinates.top  + direction*10,
            left: coordinates.left + direction*10
        };
    });
});