jQuery源码分析15: .scrollTop()与.scrollLeft()

jQuery源码分析15: .scrollTop()与.scrollLeft()

// Construct the test element
var div = document.createElement("div");
container.appendChild( div );
// Figure out if the W3C box model works as expected
div.innerHTML = "";
div.style.width = div.style.paddingLeft = "1px";
jQuery.boxModel = div.offsetWidth === 2; //< 通过检测div块的offsetWidth值是否是2px来判断浏览器是否支持盒模型


function getWindow( elem ) {
//< nodeType = 9 文档节点document
//< document.defaultView reference to the window object
//< document.parentWindow reference to the container object of the window

return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false;
}


// Create scrollLeft and scrollTop methods
jQuery.each( ["Left", "Top"], function( i, name ) {
var method = "scroll" + name;

jQuery.fn[ method ] = function( val ) {
var elem, win;

//< 返回滚动条偏移量
if ( val === undefined ) {
elem = this[ 0 ];

if ( !elem ) {
return null;
}

win = getWindow( elem );

// Return the scroll offset
//< "pageXOffset" in window IE嗅探 true : 非IE, false : IE
//< window["pageXOffset"]
//< window["pageYOffset"]
/**
var x,y;
if (self.innerHeight) { // all except Explorer
x = self.innerWidth;
y = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
x = document.documentElement.clientWidth;
y = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
x = document.body.clientWidth;
y = document.body.clientHeight;
}
*/

return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ] :
elem[ method ];
}

// 设置滚动条偏移量
return this.each(function() {
win = getWindow( this );

if ( win ) {
win.scrollTo(
!i ? val : jQuery( win ).scrollLeft(),
i ? val : jQuery( win ).scrollTop()
);
} else {
this[ method ] = val;
}
});
};
});

你可能感兴趣的:(scrollTop)