1、HTML代碼:css
<div class="ui-wraper" id="Wraper"> </div>
2、CSS代碼:html
html { width: 100%; height: 100%; min-height: 350px; /*html最小高度和要自適應模塊的高度一致*/ min-width: 1000px; /*最小寬度爲須要自適應的最小寬度*/ } body { width: 100%; height: 100%; } .ui-wraper { position: absolute; width: 100%; height: 350px; margin: 0 auto; background: #76C0F1; }
3、JS代碼:ui
var uiWrapPos = { uiWrapId: '#Wraper', defaultTop: 20, //設置默認top值 init: function() { var self = this; this.setFormPos(); $(window).resize(function(){ self.setFormPos(); }); }, setFormPos: function() { var uiWrap = $(this.uiWrapId), uiWrapWidth = uiWrap.width(), //獲取自適應div寬度 uiWrapHeight = uiWrap.height(), //獲取自適應div高度 winWidth = $('html').width(), //獲取屏幕寬度 winHeight = $('html')..height(), //獲取屏幕高度 top = (winHeight - uiWrapHeight) / 2 - this.defaultTop > 0 ? (winHeight - uiWrapHeight) / 2 - this.defaultTop : (winHeight - uiWrapHeight) / 2, //設置top值 left = (winWidth - uiWrapWidth) / 2; //設置left值 uiWrap.css({ 'top': top, 'left': left }) } } $(function(){ // 位置重設 uiWrapPos.init(); });