检查用户浏览器是否支持getBoundingClientRect()函数

时间:2018-10-20 17:19:36

标签: javascript jquery html function browser

我正在考虑检查访问者浏览器是否支持getBoundingClientRect(),然后调用下面的函数,但是如果不支持,则不要调用。这是我无法使用的代码:

    var benefitpub = document.getElementById('pubbox');
    var advbox2 = document.getElementById('advbox');

    window.onscroll = function () {
       if(benefitpub.getBoundingClientRect().top == true){ if (document.documentElement.scrollTop > benefitpub.getBoundingClientRect().top) {
            benefitpub.style.visibility = 'visible';
        } else {
        	benefitpub.style.visibility = 'hidden';
        }
        }
if(advbox2.getBoundingClientRect().top == true){
        if (document.documentElement.scrollTop > advbox2.getBoundingClientRect().top) {
            advbox2.style.visibility = 'visible';
        } else {
        	advbox2.style.visibility = 'hidden';
        }
        }
    }
#advbox, #pubbox{
    margin-top: 500px;
    visibility: hidden;
}
<div id="advbox">
    Hello This is advbox
</div>

<div id="pubbox">
    Hello this is Pubbox
</div>

有什么建议吗?还是有人知道该怎么做??

预先感谢

2 个答案:

答案 0 :(得分:1)

检查功能是否存在的最简单方法是使用typeof

const pathname = window.location.pathname;
const id = pathname.split('/').reverse()[0]

const pageData = fetch(`/path/${id}`).then(response => response.json())

如果未定义if (typeof benefitpub.getBoundingClientRect === 'function') { //Client supports getBoundingClientRect() } else { //No support } ,则类型为benefitpub.getBoundingClientRect。另外,要检查是否支持此功能而不需要任何特定元素,请检查Element原型:

'undefined'

答案 1 :(得分:0)

您必须检查元素上是否存在功能getBoundingClientRect,如果不存在,则浏览器不支持该功能。示例:

var benefitpub = document.getElementById('pubbox');
if (benefitpub.getBoundingClientRect) {
  // run your code here
} else {
  // browser doesn't support it
}
相关问题