最近項(xiàng)目兼容ie8-10心得

1、ie10及以下瀏覽器添加了絕對定位的元素,綁定事件無效,需要給元素添加背景色

方法一:
ie9-10:background:rgba(255,255,255,0);
ie8:background:url(about:blank)(ie8不兼容rgba)
方法二:
設(shè)置元素背景色后設(shè)置透明度為0,(ie8:filter:alpha(opacity=0))
但是這種方式有個(gè)缺點(diǎn),如果元素內(nèi)有其他內(nèi)容,其他內(nèi)容透明度也會(huì)變成0

2、ie8-9不兼容表單placeholder屬性,通過模擬生成其它標(biāo)簽實(shí)現(xiàn)placeholder效果

function placeholderSupport() {
  return 'placeholder' in document.createElement('input');
}

function placeholderRender() {
  //兼容ie9不支持placeholder標(biāo)簽
  if (!placeholderSupport()) {   // 判斷瀏覽器是否支持 placeholder
    function GetStringNumValue(pxstr) {
      return pxstr.substring(0, pxstr.length - 2);
    }

    if ($('input[placeholder],textarea[placeholder]').parents('#formBuild-ie8').length) {
      return false;
    }
    $('input[placeholder],textarea[placeholder]').each(function () {
      var $element = $(this),
        placeholder = $element.attr('placeholder');

      if (placeholder) {
        // 文本框ID
        var elementId = $element.attr('id');
        if (!elementId) {
          var now = new Date();
          elementId = 'lbl_placeholder' + now.getSeconds() + now.getMilliseconds();
          $element.attr('id', elementId);
        }
      }
       // 添加label標(biāo)簽,用于顯示placeholder的值
      var $label = $('<label>', {
        html: $element.val() ? '' : placeholder,
        'for': elementId,
        css: {
          position: 'absolute',
          cursor: 'text',
          color: '#ccc',
          fontSize: $element.css('fontSize'),
          fontFamily: $element.css('fontFamily'),
          zIndex: 9,
        }
      }).insertAfter($element);
      // 綁定事件
      $label.addClass('ie-placeholder')
      var _setPosition = function () {
        $label.css({
          top: '7px',
          left: '30px',
        });
      };
      var _resetPlaceholder = function () {
        if ($element.val()) {
          $label.html(null);
        } else {
          _setPosition();
          $label.html(placeholder);
        }
      };
      _setPosition();
      $element.on('focus blur input keyup propertychange resetplaceholder', _resetPlaceholder);
      /**
      以下代碼可省略,為了解決點(diǎn)擊表單彈出復(fù)雜彈窗選中數(shù)據(jù)的問題,
      問題:ie9中,點(diǎn)擊input彈出復(fù)雜彈窗后選中數(shù)據(jù)賦值到input中,模擬出來的placeholder內(nèi)容還存在,導(dǎo)致選中的數(shù)據(jù)和placeholder內(nèi)容重疊
      原因:ie9的propertychange在失去焦點(diǎn)后不會(huì)觸發(fā)
      解決:使用定時(shí)器來綁定了此方法!如果認(rèn)為此方式耗性能,建議不要給該項(xiàng)添加placeholder屬性
      **/
      if (isIE9 && $element.attr('readonly')){
        $element.click(function(){
          var intervalName;
          intervalName = setInterval(function () {
            $element.trigger("propertychange");
            if ($element.val()){
              clearInterval(intervalName);
            }else{
            }
          },1000);
        });
      }
    });
  }
}

效果(ie8):


image.png

image.png

label為生成的模擬placeholder效果的標(biāo)簽。

上面css樣式可根據(jù)項(xiàng)目需求自行設(shè)置。
如上面注釋中存在的問題,ie9的propertychange在失去焦點(diǎn)后不會(huì)觸發(fā),面對類似注釋中比較復(fù)雜特殊的交互,使用了這種比較耗性能的方式解決,或者可以不要給該項(xiàng)設(shè)置placeholder,有其他更好的解決方式可以一起討論。

3、ie8-9中ajax請求不支持跨域,設(shè)置允許跨域jQuery.support.cors = true;也不支持

原因:IE10+ 才支持withCredentials屬性,IE9以下不支持,跨域?qū)ο笾荒苡肵DomainRequest對象,而jQuery并不兼容XDomainRequest。
解決:
方法一:設(shè)置ie瀏覽器配置,“工具->Internet 選項(xiàng)->安全->自定義級別”將“其他”選項(xiàng)中的“通過域訪問數(shù)據(jù)源”選中為“啟用”(不太現(xiàn)實(shí),無法操控用戶設(shè)置)
方法二:別跨域請求了,前端配個(gè)nginx轉(zhuǎn)發(fā)代理吧。(目前的項(xiàng)目采用的這種方式)
方法三:插件 jQuery-ajaxTransport-XDomainRequest,這是一個(gè)基于 XDomainRequest 實(shí)現(xiàn) jquery ajxa 的 jquery 插件,為了支持 IE8、9的cors
PS:這里只是說jquery的ajax請求,不包括XMLHttpRequest等。

4、ie8不兼容css :nth-child()

但是.........它兼容jquery的:nth-child()............
emmmmmmmm........
所以css文件中正常這么設(shè)置的樣式

.index_bg .mainmenu li:nth-child(8n+1) {background-color:#36A1DB}
.index_bg .mainmenu li:nth-child(8n+2) {background-color:#678ce1}
.index_bg .mainmenu li:nth-child(8n+3) {background-color:#8c67df}

要兼容ie8的話,在js中:

if (isIE8) { //isIE8為項(xiàng)目中設(shè)置的一個(gè)全局變量
      $('.index_bg .mainmenu li:nth-child(8n+1)').css('backgroundColor', '#36A1DB')
      $('.index_bg .mainmenu li:nth-child(8n+2)').css('backgroundColor', '#678ce1')
      $('.index_bg .mainmenu li:nth-child(8n+3)').css('backgroundColor', '#8c67df')
    }

ie8也不兼容很多css3新屬性,border-radius、box-shadow、background 背景漸變等,如果需求有這些,要么干掉需求,要么百度。

5、ie8不兼容各種操作數(shù)組或者對象很順手的api,比如filter、forEach、map、Object.assign()、Object.keys()等等等等。。。

兼容:

//filter
if (!Array.prototype.filter) {
    Array.prototype.filter = function (fun ) {
      if (this === void 0 || this === null)
        throw new TypeError();
      var t = Object(this);
      var len = t.length >>> 0;
      if (typeof fun !== "function")
        throw new TypeError();
      var res = [];
      var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
      for (var i = 0; i < len; i++) {
        if (i in t) {
          var val = t[i];
          if (fun.call(thisArg, val, i, t))
            res.push(val);
        }
      }
      return res;
    };
  }

//forEach
if (!Array.prototype.forEach) {

    Array.prototype.forEach = function forEach(callback, thisArg) {

      var T, k;

      if (this == null) {
        throw new TypeError("this is null or not defined");
      }
      var O = Object(this);
      var len = O.length >>> 0;
      if (typeof callback !== "function") {
        throw new TypeError(callback + " is not a function");
      }
      if (arguments.length > 1) {
        T = thisArg;
      }
      k = 0;
      while (k < len) {
        var kValue;
        if (k in O) {
          kValue = O[k];
          callback.call(T, kValue, k, O);
        }
        k++;
      }
    };
  }

//map
if (typeof Array.prototype.map != "function") {
    Array.prototype.map = function (fn, context) {
      var arr = [];
      if (typeof fn === "function") {
        for (var k = 0, length = this.length; k < length; k++) {
          arr.push(fn.call(context, this[k], k, this));
        }
      }
      return arr;
    };
  }

//Object.assign()
if (typeof Object.assign != 'function') {
    Object.assign = function(target) {
      'use strict';
      if (target == null) {
        throw new TypeError('Cannot convert undefined or null to object');
      }
      target = Object(target);
      for (var index = 1; index < arguments.length; index++) {
        var source = arguments[index];
        if (source != null) {
          for (var key in source) {
            if (Object.prototype.hasOwnProperty.call(source, key)) {
              target[key] = source[key];
            }
          }
        }
      }
      return target;
    };
  }

//Object.keys()
var DONT_ENUM = "propertyIsEnumerable,isPrototypeOf,hasOwnProperty,toLocaleString,toString,valueOf,constructor".split(","),
    hasOwn = ({}).hasOwnProperty;
  for (var i in {
    toString: 1
  }) {
    DONT_ENUM = false;
  }
  Object.keys = Object.keys || function (obj) {//ecma262v5 15.2.3.14
    var result = [];
    for (var key in obj) if (hasOwn.call(obj, key)) {
      result.push(key);
    }
    if (DONT_ENUM && obj) {
      for (var i = 0; key = DONT_ENUM[i++];) {
        if (hasOwn.call(obj, key)) {
          result.push(key);
        }
      }
    }
    return result;
  };

都是從網(wǎng)上擼來的兼容方案。

6、IE8不識(shí)別媒體查詢media

百度文件respond.min.js,引入到用到的文件中的條件注釋里

  <!--[if IE 8]>
  <script src="respond.min.js"></script>
  <![endif]-->

注意:媒體查詢在IE8里簡寫不生效。

7、ie中a標(biāo)簽的disabled屬性

實(shí)際上,a標(biāo)簽沒有disabled屬性
但是,如果a標(biāo)簽中添加disabled屬性,在ie中a標(biāo)簽點(diǎn)擊事件無效
(本來也沒想到會(huì)給a標(biāo)簽添加disabled屬性,奈何可愛的后端同事們自己寫功能的時(shí)候以為disabled對所有標(biāo)簽有效就亂加,以至于發(fā)現(xiàn)了這個(gè)奇怪的現(xiàn)象。)

8、console.log()在ie8中的貓膩

比較坑的一個(gè)問題,現(xiàn)在都是用的ie11仿真模式調(diào)試ie8瀏覽器,一般都是打開控制臺(tái)調(diào)試,控制臺(tái)關(guān)了之后仿真的ie8其實(shí)不準(zhǔn)確,所以開發(fā)是沒有關(guān)控制臺(tái),就沒發(fā)現(xiàn)問題。
直到項(xiàng)目組用的時(shí)候發(fā)現(xiàn)了問題,就裝了個(gè)虛擬機(jī)用真實(shí)ie8調(diào)試,發(fā)現(xiàn)某個(gè)功能有問題,f12開發(fā)者工具打開之后就正常了(也是測了很久才發(fā)現(xiàn)f12打開才正常)。
解決:刪掉console.log(),IE8會(huì)將console.log()默認(rèn)處理為錯(cuò)誤邏輯,但是在F12下處理為控制臺(tái)輸出。

持續(xù)更新中。。。。(或許)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 夜鶯2517閱讀 128,087評論 1 9
  • 我是黑夜里大雨紛飛的人啊 1 “又到一年六月,有人笑有人哭,有人歡樂有人憂愁,有人驚喜有人失落,有的覺得收獲滿滿有...
    陌忘宇閱讀 8,814評論 28 54
  • 兔子雖然是枚小碩 但學(xué)校的碩士四人寢不夠 就被分到了博士樓里 兩人一間 在學(xué)校的最西邊 靠山 兔子的室友身體不好 ...
    待業(yè)的兔子閱讀 2,759評論 2 9
  • 信任包括信任自己和信任他人 很多時(shí)候,很多事情,失敗、遺憾、錯(cuò)過,源于不自信,不信任他人 覺得自己做不成,別人做不...
    吳氵晃閱讀 6,355評論 4 8

友情鏈接更多精彩內(nèi)容