window.innerWidth-解决返回错误值的情况

时间:2019-02-16 16:36:26

标签: javascript dom window-object

tl; dr

  • 一些javascripts库依赖于窗口innerWidth |进行计算的身高;
  • window.innerWidth并非100%可靠,这可能会导致错误;
  • matchMedia()。matches的准确度为100%,但返回布尔值;
  • 过来:使用matchMedia验证window.innerWidth值;如果返回假,则使用matchMedia进行BinarySearch直到找到正确的值;

我遇到了一些依赖window.innerWidth的库的问题。在某些媒体查询的情况下,该库使用的window.innerWidth的返回值将关闭,并且该库将出现值不正确的问题。

尽管我已经看到 matchMedia()。matches 总是返回正确的值,但是它返回的是布尔值,而不是宽度值。到目前为止,我还没有看到解决方案(也许有些人知道更好的解决方案?),所以我想出了一个使用matchMedia的解决方案。

我创建了一个函数 getCorrectDimension ,该函数在窗口innerWidth(或Height)周围执行BinarySearch,以查找正确的值(如果其值错误),如下所示:

const binarySearch = dim => function bin(start, end) {
    const guess = Math.floor((start + end)/2)

    // this checks if we have the correct value, if not it will keep calling itself until there's a match
    if(window.matchMedia(`(${dim}: ${guess}px)`).matches) {
        return guess
    }

    // since it is not a match, then we need to recalibrate the range and call again.
    // for that we check the boolean value using with min-width (height) rule.
    return window.matchMedia(`(min-${dim}: ${guess}px)`).matches 
        ? bin(guess, end) 
        : bin(start, guess)
}

const getCorrectDimension = (dim = 'width', range = 300) => {
    if(dim !== 'width' && dim !== 'height') {
        throw Error('`getCorrectDimension` accepts "width" or "height" as parameter')
    }

    let prop = 'inner' + dim.charAt(0).toUpperCase() + dim.slice(1)

    // here checks if the window.innerWidth or Height it's the correct one
    if(window.matchMedia(`(${dim}: ${window[prop]}px)`).matches) {
        return window[prop]
    }

    // here, since the value is wrong we use binarySearch to find its correct value
    const start = window[prop] - range >= 0 ? window[prop] - range : 0
    const end = window[prop] + range

    return binarySearch(dim)(start, end)

}

0 个答案:

没有答案