2014-10-31 67 views
-1

我在AngularJS中通過指令實現工具提示,但無法獲取元素座標。 當我的工具提示可見時,我想獲取該位置的座標,並且想根據位置顯示它 。如何獲取angularJs指令鏈接函數中元素標籤的座標

'use strict'; 
var utility = angular.module("utility", []); 

utility.directive("tooltip", function() { 

    var directive = {}; 

    directive.restrict = 'A'; 
    directive.transclude = true; 

    directive.link = function ($scope, element, attributes) { 
     element.html("This is the new content: "); 
     element.bind('mouseenter', createDiv); 
     element.bind('mouseleave', destroyDiv); 


     function createDiv() { 

      //need the coordinate of the pointer to display div on hover of attribute. 

      var divTag = document.createElement("div"); 
      var toolTipHtml; 
      divTag.id = "divToolTip"; 
      divTag.setAttribute("align", "center"); 
      //divTag.style.border = "1px solid #ccc"; 
      divTag.style.zIndex = "999"; 
      divTag.style.position = "absolute" 
      divTag.style.width = "200px"; 
      divTag.style.height = "115px"; 
      toolTipHtml = "<div style=\" opacity:0.8; border-bottom:15px solid #000; border-left:10px solid transparent;border-right:10px solid transparent;width:0;height:0; \"></div>" 
      toolTipHtml += "<div style = \"background-color:black; opacity:0.8; border: 1px solid #F11; width:98%; height:95%; -webkit-border-radius:20px; position:relative;\">"; 
      toolTipHtml += "<div style=\" width:96%; height:10px; margin-top:15px;\"> <div style=\" float:left; width:90%; height:9px;\"></div> <div style=\" float:left; width:10%\"> <img src=\"./img/close.png\" alt=\"HTML Tutorial\"/> </div> </div>"; 
      toolTipHtml += "<div style=\"float:left; width:150px;\"/> " + $scope.toolTipData.message + "</div>"; 
      toolTipHtml += "</div>"; 

      divTag.innerHTML = toolTipHtml; 

      element.append(divTag); 
     } 

     function destroyDiv() { 
      var divTag = document.getElementById("divToolTip"); 
      divTag.remove(); 
     } 
    } 

    directive.scope = true; 

    return directive; 


}); 

回答

0

angular.elementjQuery的兼容API

如果jQuery庫包含在頁面中,它實際上使用jQuery,但這不是依賴項。

由於jQuery中任何事件處理函數的第一個參數都是事件對象,所以您需要將該參數傳遞給您的事件處理函數,然後才能訪問座標。

function createDiv(event){ 

    var pageX = event.pageX, 
     pageY = event.pageY; 

     /* your existing code */ 
} 

你也可以用它來創建和操作你的新元素。

var divTag = angular.element('<div>'); 
divTag.css({zIndex:999, position:'absolute', width: 200, height: 115}); 

參考:angular.element docs