前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >getBoundingClientReact方法

getBoundingClientReact方法

作者头像
epoos
发布2022-06-06 15:46:49
3710
发布2022-06-06 15:46:49
举报
文章被收录于专栏:epoos.comepoos.com
getBoundingClientRect方法兼容IE7写法
代码语言:javascript
复制
rectObject = object.getBoundingClientRect(); // 返回元素的大小及其相对于视口的位置

ie7中的getBoundingClientRect方法只有bottom、left、right、top属性,没有width合height

图片
图片

通过上图可以看出: 除了width和height,其它几个属性都是相对于视口的左上角而言的。

根据left、right的值可以推算出width

根据top、bottom的值可以推算出height

完整的代码如下:

代码语言:javascript
复制
/**
 * getBoundingClientRect 兼容IE7
 * @param {DOM Object} obj 
 */
function getBoundingClientRect(obj) {
    var boundingClientRect = obj.getBoundingClientRect();
    var newObj = {
        bottom: boundingClientRect.bottom,
        left: boundingClientRect.left,
        right: boundingClientRect.right,
        top: boundingClientRect.top
    }

	if (boundingClientRect.width) {
		newObj.width = boundingClientRect.width;
		newObj.height = boundingClientRect.height;
	} else {
		newObj.width = boundingClientRect.right - boundingClientRect.left;
		newObj.height = boundingClientRect.bottom - boundingClientRect.top;
    }
	return newObj;
}

相关链接

getBoundingClientRect

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-03-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 相关链接
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档