Javascript:IE8 中变量对象属性问题的参数无效

标签 javascript internet-explorer object

我正在尝试动态设计这样的元素

var element = document.querySelector('.myElement');
var prop = 'left'; // this is incoming property variable computed by other code
var leftTop = ['left','top'];
var widthHeight = ['width','height'];



if (prop === 'left' || prop === 'top') {
   element.style[prop] = 20+'px'; // the condition determines that left/top property is to be used
} else {
   element.style[prop] = 40+'px'; // the condition determines that width/height property is to be used
}      

错误是:

SCRIPT87: Invalid argument. File: script.js, Line: 275, Column: 5

我知道当条件满足时我可以使用 element.style.left ,并且 IE8 可以完成这项工作,但在我的例子中,数组变量包含 20 多个属性,我真的需要让它工作与 element.style[prop].

感谢您的任何建议或解决方案。

最佳答案

你需要把 var element = document.querySelector('.myElement'); 到您的 window.onload 中。您现在所拥有的是在元素存在之前抓取 .myElement 。如果您需要保持全局,那么只需定义为:

var element;
window.onload = function(){
    element = document.querySelector('.myElement');
    if (prop === 'left' || prop === 'top') {
        element.style[prop] = 20+'px'; // the condition determines that left/top property is to be used
    } else {
        element.style[prop] = 40+'px'; // the condition determines that width/height property is to be used
    }   
};

摆弄错误:http://jsfiddle.net/a9fms3um/ fiddle 没有错误:http://jsfiddle.net/a9fms3um/1/ 还要确保该元素确实与页面上的该类一起存在。

关于Javascript:IE8 中变量对象属性问题的参数无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32381250/

相关文章:

javascript - 需要代码返回数组坐标

javascript - 更改页面而不刷新页面中的 div

Javascript 表单验证器功能无法正常工作

jquery - TinyMCE 在 IE8 中出现故障/无法使用

java - 为什么我无法在函数内创建数组对象?

Java,当你执行 object = object 时内部发生了什么?

javascript - 对多个 Twitter 帐户使用 Twitter API Stream?

javascript - Dropdown Onchange 并将 JavaScript 值传递给 PHP

internet-explorer - 在 IE 中选择 StartContainer

c# - 更改 Internet Explorer 安全设置(初始化和脚本 activex 控件不裸...)