getBoundingClientRect函數獲取視圖位置的坑

 

最近在做一個功能,把新手引導的提示定位在申請的上方,申請的位置是會根據前面功能的不展示而向前移動的,所以位置是不固定的,因此新手引導的位置要根據申請元素的位置來定位。

我使用了getBoundingClientRect函數來獲取申請dom元素距離視圖的距離。

    getTypeHighLightDom(item) {
        const dom = document.querySelector(item.selector);
        let domLocal;
        dom && (domLocal = dom.getBoundingClientRect());

        return (
            <div
                key={item.selector}
                style={{
                    position: 'absolute',
                    top: domLocal.y - parseInt(domWidth) * 0,
                    left: domLocal.x - parseInt(domWidth) * 0.6,
                    width: parseInt(domLocal.width) * 1.8 + 'px'
                }}
            >
                <img style={{width: '120%'}} src={item.pic} alt=""/>
            </div>
        )
    }

結果在chrome和高版本的瀏覽器中顯示是正常的,但是在一些低版本的手機自帶的瀏覽器以及低版本的safari中顯示就錯位了,一開始的猜想應該是因爲瀏覽器的版本沒有獲取到dom元素或者是元素的距離。

然後在控制檯打印如下:

設置的元素的樣式的top和left不起作用,跟getBoundingClientRect函數的x.y屬性有關,所以在IE和Idge中打印屬性,發現沒有此屬性,也查閱了資料發現

IE和Idge瀏覽器不支持x、y屬性

IE9版本以下的瀏覽器不支持width、height屬性。

當然還有一些其他瀏覽器的不兼容,各位在開發時可以判斷一下。

然後我改進代碼如下,在手機上就顯示正常了。

    getTypeHighLightDom(item) {
        const dom = document.querySelector(item.selector);
        let domLocal;
        //在IE和Edge中getBoundingClientRect函數返回的對象無x、y屬性,使用left和top代替
        dom && (domLocal = dom.getBoundingClientRect());
        //IE低版本無width和height 屬性,使用right和left來計算
        let domWidth = domLocal.right - domLocal.left;

        return (
            <div
                key={item.selector}
                style={{
                    position: 'absolute',
                    top: domLocal.top - parseInt(domWidth) * 0,
                    left: domLocal.left - parseInt(domWidth) * 0.6,
                    width: parseInt(domWidth) * 1.8 + 'px'
                }}
            >
                <img style={{width: '120%'}} src={item.pic} alt=""/>
            </div>
        )
    }


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章