qiuhongbingo / blog

Writing something in Issues.
https://github.com/qiuhongbingo/blog/issues
3 stars 0 forks source link

适配器模式在前端中的应用 #26

Open qiuhongbingo opened 4 years ago

qiuhongbingo commented 4 years ago
/**
 * 适配器模式在于适配两个及以上类接口不兼容的问题,和外观模式的核心思路类似
 * 例如 jQuery 里适配 opacity
 */

/**
 * 在 Chrome 4+、FF2+、Saf3.1+、Opera 9+、IE9、iOS 3.2+、Android 2.1+ 中:
 * opacity: 0.9
 */

/**
 * 但是在 IE6-8,却是:
 * filter: alpha(opacity=90)
 */

/**
 * jQuery 利用适配器模式,对这种差异进行了抹平:
 */
$('.container').css({ opacity: 0.5 })

// 内部实现
export default {
  get: function(elem, computed) {
    return ropacity.test((computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || '')
      ? parseFloat(RegExp.$1) / 100 + ''
      : computed
      ? '1'
      : ''
  },
  set: function(elem, value) {
    var style = elem.style
    var currentStyle = elem.currentStyle
    var opacity = jQuery.isNumeric(value) ? 'alpha(opacity=' + value * 100 + ')' : ''
    var filter = (currentStyle && currentStyle.filter) || style.filter || ''
    style.zoom = 1
    if (value >= 1 && jQuery.trim(filter.replace(ralpha, '')) === '') {
      style.removeAttribute('filter')
      if (currentStyle && !currentStyle.filter) return
    }
    style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : filter + ' ' + opacity
  }
}