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

Javascript: invalid argument in IE8 issue with variable object properties

本文关键字:无效 参数 问题 属性 变量 对象 IE8      更新时间:2023-09-26

我想动态设置一个元素的样式

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:无效参数。文件:script.js,行:275,列: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/摆弄没有错误:http://jsfiddle.net/a9fms3um/1/还要确定该元素与页面上的该类一起存在。