Home >Web Front-end >JS Tutorial >GetBoundingClientRect usage method and compatibility processing
This time I will bring you how to use getBoundingClientRect and compatibility processing. What are the precautions about how to use getBoundingClientRect and compatibility processing. The following is a practical case, let’s take a look.
The role of getBoundingClientRect
getBoundingClientRect is used to obtain the position set of a html element relative to the view window.
Executing object.getBoundingClientRect(); will get the top, right, bottom, left, width, and height attributes of the element. These attributes are returned as a object.
getBoundingClientRect()
This method returns a rectangle object containing four properties: left, top, right and bottom. Represents the distance between each side of the element and the top and left sides of the page respectively.
var box=document.getElementById('box'); // 获取元素 alert(box.getBoundingClientRect().top); // 元素上边距离页面上边的距离 alert(box.getBoundingClientRect().right); // 元素右边距离页面左边的距离 alert(box.getBoundingClientRect().bottom); // 元素下边距离页面上边的距离 alert(box.getBoundingClientRect().left); // 元素左边距离页面左边的距离
Browser Compatibility
It can be supported by ie5 and above, but there are a few things that need to be corrected,
IE67's left and top will be 2px less, and there will be no width or height attributes.
Use getBoundingClientRect to write a method to obtain the position set of html elements relative to the window
<p id="test" style="width: 100px; height: 100px; background: #ddd;"></p> <script> function getObjXy(obj){ var xy = obj.getBoundingClientRect(); var top = xy.top-document.documentElement.clientTop+document.documentElement.scrollTop,//document.documentElement.clientTop 在IE67中始终为2,其他高级点的浏览器为0 bottom = xy.bottom, left = xy.left-document.documentElement.clientLeft+document.documentElement.scrollLeft,//document.documentElement.clientLeft 在IE67中始终为2,其他高级点的浏览器为0 right = xy.right, width = xy.width||right - left, //IE67不存在width 使用right - left获得 height = xy.height||bottom - top; return { top:top, right:right, bottom:bottom, left:left, width:width, height:height } } var test = getObjXy(document.getElementById('test')); alert("top:" + test.top + ", right:" + test.right + ", bottom:" + test.bottom + ", left:" + test.left); </script>
I believe you have mastered the method after reading the case in this article. Please come for more exciting information. Pay attention to other related articles on php Chinese website!
Recommended reading:
Vue implements the parabola effect of the small ball in the shopping cart Detailed explanation
Detailed explanation of the use of components in Vue.js
The above is the detailed content of GetBoundingClientRect usage method and compatibility processing. For more information, please follow other related articles on the PHP Chinese website!