my$("btn").onclick = function () { //获取元素距离左边位置的值 console.log(my$("dv").offsetLeft); //谷歌,火狐支持 //console.log(window.getComputedStyle(my$("dv"),null).left); //console.log(window.getComputedStyle(my$("dv"),null)["left"]); //IE8支持 //console.log(my$("dv").currentStyle.left); };
所以封装一个兼容函数,判断浏览器是否支持再返回浏览器
function getStyle(element, attr) { //判断浏览器是否支持这个方法 return window.getComputedStyle ? window.getComputedStyle(element, null)[attr] : element.currentStyle[attr]; }
测试:函数
//测试 my$("btn").onclick = function () { console.log(getStyle(my$("dv"), "top")); };