我正在尝试动态设计这样的元素
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/