javascript - IE8获取元素样式坐标的方法

标签 javascript css internet-explorer-8

我已经为此苦苦思索了一段时间,所以我需要聪明人的帮助。

我正在努力提取元素中“背景位置”值的 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 模式(在开发者控制台中这样说)。其中大部分在 Chrome 和 Mozilla 中工作得很好。我正在 IE8 中进行测试,因为我的客户仍在使用 IE 8。此外,服务器端代码(这是我没有完全权限的共享点服务器)似乎正在强制页面以 IE8 模式显示。

我还尝试添加 html5 标签 <!doctype html>可能会强制浏览器以 html5 呈现。仍然停留在IE8模式。无论如何,任何人都可以指出一个可以工作并在 IE8 中提取像素值的 DOM API 调用吗?

最佳答案

我制作了一个测试页面,其中 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

关于javascript - IE8获取元素样式坐标的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36708848/

相关文章:

javascript - Google 日历事件观看错误 401 未经服务帐户授权

javascript - Tizen 可穿戴 Web 应用程序 : Content getting smaller when not in the center of the screen

Javascript 未按预期运行。无法确定原因。

css - Stylus 中@font-face 的正确语法/使用 stylus-font-face npm

internet-explorer-8 - Selenium + IE8 : force IE8 compatibility view

javascript - 为什么IE8不处理iframe onload事件?

javascript - Youtube上传小部件onApiReady无法启动

javascript - 使用 javascript 更改基本 href

css - :nth-child(1) versus :first-child in css pseudo selectors are there any merits in choosing one method over the other?有什么区别

javascript - 如何判断 IE8 窗口何时失去焦点?