2016-04-19 34 views
0

我一直在这里嘲笑我一段时间,所以我需要一些聪明人的帮助。如何在IE8中获取元素的样式坐标

我很努力地提取我的元素中的'background-position'值的xy坐标。为了测试这一点,我设置此(css_class =预定的CSS类):

var d = document.getElementById(css_class); 

alert("1: "+getStyle(d,'background-position')); 
alert("2: "+d.style.backgroundPosition); 
alert("3: "+d.currentStyle.backgroundPosition); 
alert("4: "+d.style.cssText); 
alert("5: "+window.getComputedStyle(d,null).getPropertyValue('background-position')); 

test1--> undefined 
test2--> blank 
test3--> undefined 
test4--> blank 
test5-->'Object doesn't support property or method 'getComputedStyle'' 

没有给我回来在xy像素值。很明显,我已经完成了我的研究,通过我可以找到的所有微软DOM API参考(这是我获得getStyle函数(下面,还使用getComputedStyle),搜索了一些mozilla开发人员论坛等的地方。) 这是函数我在这个论坛中发现:

function getStyle(el,styleProp) { 
     var camelize = function (str) { 
      return str.replace(/\-(\w)/g, function(str, letter){ 
       return letter.toUpperCase(); 
       }); 
      }; 

      if (el.currentStyle) { 
      return el.currentStyle[camelize(styleProp)]; 
      } else if (document.defaultView && document.defaultView.getComputedStyle) { 
      return document.defaultView.getComputedStyle(el,null) 
             .getPropertyValue(styleProp); 
      } else { 
      return el.style[camelize(styleProp)]; 
      } 
     } 

基本上我敢肯定,这个问题是因为我的IE浏览器11恢复到IE8模式(是这么说的在开发者控制台)在大多数浏览器和Mozilla就好了这些工作。我在IE8中测试,因为我的客户仍然使用IE 8.同样,服务器端代码(这是我没有完全权限的sharepoint服务器)强制页面在IE8模式下显示。

我也尝试添加html5标记<!doctype html>,以便强制浏览器在html5中呈现。仍然坚持IE8模式。无论如何,任何人都可以指向我的DOM API调用,将工作,并在IE8中拉出像素值?

回答

0

我做了一个测试页,其中background-position以内联样式定义,我可以在.style.backgroundPosition属性中选择它。 (我也有点击一个按钮启用JavaScript,因为它是一个本地文件。)

<html> 
<head> 
    <meta http-equiv="x-ua-compatible" content="ie=8"> 
    <title>ie8 test</title> 
</head> 
<body> 
    <div id="a" style="width: 200px; height: 200px; border: 1px outset gray; background-image: url('./Untitled.png'); background-position: 10px 10px;"></div> 
    <script> 
     document.write(document.getElementById("a").style.backgroundPosition); 
    </script> 
</body> 
</html> 

Screenshot of IE11's developer tools, showing the value of document.getElementById("a").style.backgroundPosition