2014-09-05 49 views
0

我目前正在使用Polymer構建自定義元素。現在我想獲得一個位於我的自定義元素中的div來執行某個函數onclick,並且在該函數中我需要獲取它相對於視圖端口的位置。聚合物 - 獲得位於陰影dom的divs位置

所以通常我會用

var offsets = element.getBoundingClientRect(); 

現在,在自定義元素 - 假設我說的有ID innerCard股利所以這將是

this.$.innerCard.onclick = function(){ 
alert("Test 1"); 
var offsets = this.$.innerCard.shadowRoot.getBoundingClientRect(); 
alert("Test 2"); 
.... 
} 

第一警報觸發正確,但第二個沒有。 JavaScript控制檯給了我一個錯誤類型:

Uncaught TypeError: Cannot read property 'innerCard' of undefined tile-story.html:37$.innerCard.onclick tile-story.html:37 

有誰知道我怎麼能以其他方式或我在做什麼錯在這裏訪問的div的位置?

+0

能innerCard提供公共函數返回其偏移? – imcg 2014-09-05 11:06:41

+0

我不完全確定你的意思。我只是宣佈了這樣一個div:

Content_here
Escapado 2014-09-05 11:10:59

+0

如何綁定您的處理程序的'this'第一? – cameron 2014-09-05 11:29:01

回答

2

未定義的錯誤是因爲在onclick處理程序,this不一樣外this,因此,如果您要使用this.$,你應該首先結合上下文:

Polymer('tile-story', { 
     ready: function() { 
      this.$.innerCard.onclick = function() { 
       var offsets = this.$.innerCard.getBoundingClientRect(); //ClientRect {height: 18, width: 1350, left: 8, bottom: 44, right: 1358…} 
      }.bind(this); 
     } 
    }); 
+0

非常感謝。對我而言,這是我認爲最方便的做法。 – Escapado 2014-09-05 12:20:29

+0

而不是使用'.onclick',您應該將偵聽器附加到您的模板中。例如。 '

...
',那麼你可以在名爲'cardTap'的元素中聲明一個方法來完成這項工作:'cardTap:function(){var偏移量= this。$。innerCard.getBoundingClientRect()...},'。我建議'tap'而不是'click',因爲它可以用於touchevents,但是你可以在我的例子中用'click'替換'tap',它也可以工作。 – 2014-09-05 15:46:31

0

要獲取有關組件的信息,您可以在組件本身上提供公共方法。根據你的使用情況下,這將返回clientRect組件內一個div:

<x-card></x-card> 

<polymer-element name="x-card"> 
    <template> 
     <div id="innerCard" class="card">Content_here</div> 
    </template> 
    <script> 
     Polymer('x-card', { 
      getBoundingClientRect: function() { 
       return this.$.innerCard.getBoundingClientRect(); 
      } 
     }); 
    </script> 
</polymer-element> 

<script> 
    window.addEventListener('polymer-ready', function() { 
     var card = document.querySelector('x-card'); 
     var rect = card.getBoundingClientRect(); 
     console.log(rect); // {height: 18, width: 336, left: 8, bottom: 26, right: 344…} 
    }); 
</script> 

Working example here

+1

謝謝你的例子。我已經開始工作了,但是我想我最終會使用下面的那個,因爲這對我來說更容易。 – Escapado 2014-09-05 12:21:03

+0

Fwiw,這個答案是錯誤的,這個例子實際上是壞的。 '#innerCard' div不在'