利用jq讓你的div居中的好方法分享
very short version:
$('#myDiv').css({top:'50%',left:'50%',margin:'-'+($('#myDiv').height() / 2)+'px 0 0 -'+($('#myDiv').width() / 2)+'px'});
short version:
(function($){
$.fn.extend({
center: function () {
return this.each(function() {
var top = ($(window).height() - $(this).outerHeight()) / 2;
var left = ($(window).width() - $(this).outerWidth()) / 2;
$(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});
});
}
});
})(jQuery);
Activated by this code :
$('#mainDiv').center();
PLUGIN VERSION
(function($){
$.fn.extend({
center: function (options) {
var options = $.extend({ // Default values
inside:window, // element, center into window
transition: 0, // millisecond, transition time
minX:0, // pixel, minimum left element value
minY:0, // pixel, minimum top element value
withScrolling:true, // booleen, take care of the scrollbar (scrollTop)
vertical:true, // booleen, center vertical
horizontal:true // booleen, center horizontal
}, options);
return this.each(function() {
var props = {position:'absolute'};
if (options.vertical) {
var top = ($(options.inside).height() - $(this).outerHeight()) / 2;
if (options.withScrolling) top += $(options.inside).scrollTop() || 0;
top = (top > options.minY ? top : options.minY);
$.extend(props, {top: top+'px'});
}
if (options.horizontal) {
var left = ($(options.inside).width() - $(this).outerWidth()) / 2;
if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;
left = (left > options.minX ? left : options.minX);
$.extend(props, {left: left+'px'});
}
if (options.transition > 0) $(this).animate(props, options.transition);
else $(this).css(props);
return $(this);
});
}
});
})(jQuery);
Activated by this code :
$(document).ready(function(){
$('#mainDiv').center();
$(window).bind('resize', function() {
$('#mainDiv').center({transition:300});
});
);
相關(guān)文章
基于jQuery的$.getScript方法去加載javaScript文檔解析
下面小編就為大家?guī)硪黄趈Query的$.getScript方法去加載javaScript文檔解析。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-11-11簡單談?wù)刯Query(function(){})與(function(){})(jQuery)
這篇文章主要簡單介紹了jQuery(function(){})與(function(){})(jQuery)的區(qū)別,需要的朋友可以參考下2014-12-12jQuery阻止移動(dòng)端遮罩層后頁面滾動(dòng)
本文主要介紹了jQuery阻止移動(dòng)端遮罩層后頁面滾動(dòng)的方法。具有很好的參考價(jià)值。下面跟著小編一起來看下吧2017-03-03jQuery+CSS實(shí)現(xiàn)的標(biāo)簽頁效果示例【測試可用】
這篇文章主要介紹了jQuery+CSS實(shí)現(xiàn)的標(biāo)簽頁效果,涉及基于jQuery的事件綁定、頁面元素屬性動(dòng)態(tài)操作相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-08-08jq stop()和:is(:animated)的用法及區(qū)別(詳解)
下面小編就為大家?guī)硪黄猨q stop()和:is(:animated)的用法及區(qū)別(詳解)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-02-02jquery調(diào)用wcf并展示出數(shù)據(jù)的方法
網(wǎng)上看了很多jquery調(diào)用wcf的例子,可能是主機(jī)的原因,我用的是gd主機(jī),所以都沒有成功,昨天自己搞了一天,終于成功了,現(xiàn)把方法和代碼和大家分享2011-07-07