以下是我想要實現的:我有一箇中心圓div,其中包含5個其他div。當我在伽馬軸上旋轉設備時,我想讓圓形div根據伽瑪度旋轉,但是5個內部div在相反方向旋轉(這樣會產生內部div實際上不旋轉的錯覺,摩天輪效應)。我寫了這個代碼:Uncaught TypeError:未能在'Window'上執行'getComputedStyle':參數1不是'Element'類型
document.addEventListener("DOMContentLoaded",onload);
function onload(){
if (window.DeviceOrientationEvent) {
console.log("DeviceOrientation is supported");
window.addEventListener('deviceorientation', function(eventData){
var tiltLR = eventData.gamma;
deviceOrientationHandler(tiltLR);
}, false);
} else {
console.log("DeviceOrientation NOT supported");
}
}
var lastTilt = 0;
function deviceOrientationHandler(tiltLR) {
var circle = document.getElementById('center-circle');
var str = window.getComputedStyle(circle, null);
var trans = str.getPropertyValue("-webkit-transform");
var tr_values = trans.split('(')[1],
tr_values = tr_values.split(')')[0],
tr_values = tr_values.split(',');
circle.style.webkitTransform = "translate("+tr_values[4]+"px, "+tr_values[5]+"px) rotate("+ tiltLR +"deg)"
var icons = document.getElementsByClassName('icon-circle');
tiltLR = Math.abs(tiltLR);
for (var i = 0; i <= icons.length; i++){
var el = icons[i];
var st = window.getComputedStyle(el, null);
var tr = st.getPropertyValue("-webkit-transform");
var values = tr.split('(')[1],
values = values.split(')')[0],
values = values.split(',');
if (tiltLR > lastTilt) {
icons[i].style.webkitTransform = "translate("+values[4]+"px, "+values[5]+"px) rotate(-"+ tiltLR +"deg)";
} else {
icons[i].style.webkitTransform = "translate("+values[4]+"px, "+values[5]+"px) rotate("+ tiltLR +"deg)";
}
console.log("el"+i+": "+tr+" | vals: "+values);
}
lastTilt = tiltLR;
}
的問題是for
循環中 - 當代碼到達此行var st = window.getComputedStyle(el, null);
我收到以下錯誤消息:Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'
。我試圖將el
var更改爲icons[i].id
,但它沒有幫助。
任何想法,爲什麼它的發生和如何解決它?
當你循環到'i <= icons.length'時,你超過數組一個。 – JJJ
你能給我們一個[小提琴](http://jsfiddle.net/)嗎? – halex
@Juhana謝謝!簡直不敢相信我錯過了! – Igal