随滚动居中的效果,平时都会经常使用到,于是写成一个 jQuery 的插件。同时,这是我写的第一个插件。呵呵。纪念一下。
该插件可以令所选择的 Elements 永远浮动在窗口中央,无论是滚动还是窗口的大小发生改变。
代码
(function($){
$.fn.extend({
// 兼容不同的浏览器取得窗口的大小
getWindowSize: function(){
if($.browser.opera){
return {width: window.innerWidth, height: window.innerHeight};
}
return {width: $(window).width(), height: $(window).height()};
},
// 主函数
scrollCenter: function(options){
// 扩展参数
var op = $.extend({
z: 1000000
}, options);
// 追加到 document.body 并设置其样式
var windowSize = this.getWindowSize();
this.appendTo(document.body).css({
'position': 'absolute',
'z-index': op.z,
'top': (windowSize.height - this.height())/2+$(window).scrollTop() + 'px',
'left': (windowSize.width - this.width())/2+$(window).scrollLeft() + 'px'
});
// 保存当前位置参数
var bodyScrollTop = $(document).scrollTop();
var bodyScrollLeft = $(document).scrollLeft();
var movedivTop = this.offset().top;
var movedivLeft = this.offset().left;
var thisjQuery = this;
// 滚动事件
$(window).scroll(function(e){
var tmpBodyScrollTop = $(document).scrollTop();
var tmpBodyScrollLeft = $(document).scrollLeft();
movedivTop += tmpBodyScrollTop - bodyScrollTop;
movedivLeft += tmpBodyScrollLeft - bodyScrollLeft;
bodyScrollTop = tmpBodyScrollTop;
bodyScrollLeft = tmpBodyScrollLeft;
// 以动画方式进行移动
thisjQuery.stop().animate({
'top': movedivTop + 'px',
'left': movedivLeft + 'px'
});
});
// 窗口大小重设事件
$(window).resize(function(){
var windowSize = thisjQuery.getWindowSize();
movedivTop = (windowSize.height - thisjQuery.height())/2+$(document).scrollTop();
movedivLeft = (windowSize.width - thisjQuery.width())/2+$(document).scrollLeft();
thisjQuery.stop().animate({
'top': movedivTop + 'px',
'left': movedivLeft + 'px'
});
});
return this;
}
});
})(jQuery);
使用方法
$(selector).scrollCenter();
$(selector).scrollCenter({z:1000000});
参数 z 是设置其 z-index(默认设为1000000),以免被其它的层所遮盖。
兼容性
支持 IE 6.0+, FF2+, Safari 3.1+, Opera 9.0+ 。
示例
后记
遇到的问题主要还是浏览器的兼容性问题,取得窗口大小的方法上,IE、FF、Safari 浏览器都可以通过 $(window).width() 和 $(window).height() 来取得窗口的宽和高。但在 Opera 上,只能通过 window.innerWidth 和 window.innerHeight。