zepto icon indicating copy to clipboard operation
zepto copied to clipboard

The setter of offset is wrong.

Open 2betop opened this issue 12 years ago • 1 comments

The setter of offset is wrong when trying to position an element with position static which is not the first no absolute positioning element.

Please try the following test case.

testOffsetSetter: function(t){
  var el = $('#some_element').append('<p>Element one</p><p>Element two</p>').css('position', 'relative')

  var p = el.children().eq(1).offset({top: 30, left:30})

  t.assertEqual(p.offset().left, 30)
  t.assertEqual(p.offset().top, 30)

  // reset
  el.css('position', 'static').empty()
}

2betop avatar Aug 05 '13 01:08 2betop

I fixed it in my project with the following code. I hope this can be fixed in zepto.js. Thx.

$.fn.offset = function( coord ) {
    var hook;

    hook = coord && function() {
        var $el = $( this ),
            position = $el.css( 'position' ),
            pos = position === 'absolute' || position === 'fixed' ||
                $el.position();

        coord = typeof coord === 'function' ?
                coord.apply( this, arguments ) : coord;

        if ( position === 'relative' ) {
            pos.top -= parseFloat( $el.css( 'top' ) ) || 
                    parseFloat( $el.css( 'bottom' ) ) * -1 || 0;
            pos.left -= parseFloat( $el.css( 'left' ) ) ||
                    parseFloat( $el.css( 'right' ) ) * -1 || 0;
        }

        coord = {
            top: coord.top - (pos.top || 0),
            left: coord.left - (pos.left || 0)
        };

        return coord;
    };

    return _offset.call( this, hook );
};

2betop avatar Aug 05 '13 01:08 2betop