2015-01-04 3 views
2

요소를 깜박이는 JS 함수를 만들려고합니다. 타이밍에 setInterval()을 사용하지만 오류 메시지는 Uncaught TypeError: Cannot read property 'opacity' of undefined입니다. 내가 잘못 뭐하는 거지Javascript element.style.opacity가 정의되지 않았습니다. 왜?

내가 타이머하지 불투명도를 수정하려고하지만, 작동, "손으로"...

?

용도 :

document.getElementById('idOfTheElement').startFlicker(); 

함수 :

Element.prototype.startFlicker = function() { 
    var blinkInterval = setInterval(function() { 
     if (parseInt(this.style.opacity) === 0) { 
      this.style.opacity = 1; 
     } else { 
      this.style.opacity = 0; 
     } 
    }, 50); 
}; 
+0

귀하의 '이'는 귀하가 생각하는 것과 다릅니다. 간격 안에 범위를 벗어났습니다. – mplungjan

답변

3

Element.prototype.startFlicker = function() { 
    var self = this; 

    var blinkInterval = setInterval(function() { 
     if (parseInt(self.style.opacity) === 0) { 
      self.style.opacity = 1; 
     } else { 
      self.style.opacity = 0; 
     } 
    }, 50); 
}; 

setIntervalthis가지칭하여 시도, 변수에 상점 컨텍스트 (this - 현재 요소)가 필요하며 setInterval

1

컨텍스트로 인해. setInterval 내의 this.style은 글로벌 window 개체를 나타냅니다.

0

setInterval 함수 내에서 창 개체가 this으로 전달되므로 항상 요소 자체에 대한 참조를 만들 수 있습니다.

대신 .bind()을 시도해야합니다. 따라서 this은 메소드의 인수에 대한 참조 일 것입니다.

Element.prototype.startFlicker = function() { 
    var blinkInterval = setInterval(function() { 
     if (parseInt(this.style.opacity) === 0) { 
      this.style.opacity = 1; 
     } else { 
      this.style.opacity = 0; 
     } 
    }.bind(this), 50); 
}; 
관련 문제