关于火狐下的兼容问题解决方法

本文最后更新于:2023年3月30日 下午

前一篇文章 关于火狐下的兼容问题中我们可以知道offsetleft/top/width/height会出现兼容问题,具体兼容问题可以去关于火狐下的兼容问题观看,今天我们为大家讲解怎么解决他,为什么会出现这个问题呢,因为offset获取这些值时包含了bordermarginpadding等值,所以我们要来正面解决他而不是规避他;

这里写一个函数:

1
2
3
4
5
6
function getStyle(obj, attr) {
return obj.currentStyle ?
obj.currentStyle[attr] // 兼容ie
:
getComputedStyle(obj,false)[attr]; // 高级浏览器
}

以后获取这些值是大家都用它来获取保证没错

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
*{margin: 0;padding: 0;list-style: none}
#fu{ position: relative;width: 300px;height: 200px;margin: 100px auto 0px;background: #f40;}
#zi{ position: absolute;left: 0;top:0; width: 200px;height: 100px;background: pink;left:0px;}
.cur{border:20px solid #ccc;overflow: hidden;}
</style>
<script>
function getStyle(obj, attr) {
return obj.currentStyle
? obj.currentStyle[attr] // 兼容ie
: getComputedStyle(obj, false)[attr]; // 高级浏览器
}
window.onload = function() {
var zi = document.getElementById('zi');
console.log(getStyle(zi, 'left'));
// 现在是-1;如果去掉父级#fu的class=“cur”,则打印出来时0
// border:1px solid #ccc;overflow: hidden;会对定位产生影响?求解答......
}
</script>
</head>
<body>
<div id="fu" class="cur">
<div id="zi"></div>
</div>
</body>
</html>

看到了吗是不会有问题的,大家都用getStyle(obj, attr);方法吧


关于火狐下的兼容问题解决方法
https://seven3.site/js/关于火狐下的兼容问题解决方法/
作者
Seven3s
发布于
2015年1月27日
许可协议