你的位置:首页 > Java教程

[Java教程]【高度自适应】基于像素(px)为单位的高度自适应,适合单屏页面


/*基于像素(px)为单位的高度自适应,适合单屏页面*///设置高度(延伸到浏览器底部 或 延伸到参考元素底部,可以设置减少量)$.fn.fnSetHeight = function(A, B) {  if (this.length > 0) {    //参数处理    var $Reference, Decrease;    switch (arguments.length) {      case 0:        $Reference = $(window);        Decrease = 0;        break;      case 1:        if (typeof A === 'number') {          $Reference = $(window);          Decrease = A;        } else {          $Reference = $(A).eq(0);          Decrease = 0;        }        break;      default:        $Reference = $(A).eq(0);        Decrease = B;    }    //设置高度    if ($Reference.length > 0) {      var isWindow = $Reference[0] === window;      this.each(function() {        var setHeight = function(target) {          var $target = $(target);          var ta_offsetTop = $target.offset().top,            re_offsetTop = isWindow ? 0 : $Reference.offset().top;          var ta_top = parseInt($target.css('padding-top')) + parseInt($target.css('border-top-width')),            re_top = isWindow ? 0 : parseInt($Reference.css('padding-top')) + parseInt($Reference.css('border-top-width'));          var h = $Reference.height() + re_top - (ta_offsetTop - re_offsetTop) - ta_top - Decrease;          $target.height(parseInt(h));        };        setHeight(this);        //为窗体的resize事件作准备(在闭包里为DOM添加方法与属性)        if (!this.ExecutionSequence) {          if (!window.__SetHeightExecutionSequence) window.__SetHeightExecutionSequence = 1;          this.setHeight = function() { //给DOM添加方法:设置高度            setHeight(this);          };          this.ExecutionSequence = window.__SetHeightExecutionSequence; //给DOM添加属性:记录执行顺序          window.__SetHeightExecutionSequence++;          $(this).addClass('resize-setHeight');        }      });    }  }  return this;};//对窗体的resize事件进行包装,防止多次触发window.Win_resize = function(Func, Time) {  var isRun = true,    time = Time !== 0 ? Time || 250 : 0;  $(window).resize(function(e) {    if (isRun) {      isRun = false;      setTimeout(function() {        isRun = true;        Func(e);      }, time);    }  });};//对当前可见的视图进行高度自适应window.$CurrentView = $(); //该选择器需要在相应的事件里被更新 ...window.ResizeSetHeight = function() {  var $target = $CurrentView.find('.resize-setHeight:visible');  var ArrayDOM = $.makeArray($target);  //按执行顺序排队  ArrayDOM.sort(function(a, b) {    return a.ExecutionSequence - b.ExecutionSequence;  });  //出列执行  for (var i = 0; i < ArrayDOM.length; i++) {    ArrayDOM[i].setHeight();  }};//绑定事件Win_resize(ResizeSetHeight, 500); //窗体resize时高度自适应$('#xxx').on('click', '.xxx', function() { //其它事件时高度自适应,比如标签页切换时 ...  if (xxx) {    $(window).resize(); //或:ResizeSetHeight();  }});//setHeight使用情况,选择器可以是:字符串 || jQ对象 || DOM对象 $('#xxx').fnSetHeight(); //延伸到浏览器底部$('#xxx').fnSetHeight(20); //延伸到浏览器底部,并减少20px$('#xxx').fnSetHeight('#reference'); //延伸到参考元素底部$('#xxx').fnSetHeight('#reference', 20); //延伸到参考元素底部,并减少20px