簡體   English   中英

Javascript:IE8中的無效參數帶有可變對象屬性

[英]Javascript: invalid argument in IE8 issue with variable object properties

我正在嘗試動態設置這樣的元素

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
}      

錯誤是:

腳本87:無效的參數。 文件: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/還要確保該元素確實存在於頁面上。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM