错误:当试图使用Raphael获取元素的位置时,this.attr不是函数

Error : this.attr is not a function when trying to get the position of an element using Raphael

本文关键字:位置 this attr 函数 元素 获取 Raphael 错误      更新时间:2023-09-26

我是Rapahel的新手,我正在尝试获取元素单击时的位置。请在下面找到代码片段。它给了我一个错误,说this.attr不是函数。我确信我做错了,请告知。

    <html>
<head>
    <title>Raphael Test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <script type="text/javascript" src="raphael.js"></script>
    </head>
    <body>
    <script type="text/javascript">
    window.onload = function initPage() {
        var paper = new Raphael(document.getElementById('holder'), 1200, 500); 
        var nodeHeader = paper.rect(100,100,150,50,10);
        nodeHeader.attr({  
                        gradient: '90-#6BAA3A-#409400',  
                        stroke: '#6BAA3A',  
                        'stroke-width': 1, 
                        cursor: "move" 
                        });
        nodeHeader.node.id='nodeHeader';
        nodeHeader.node.onclick = function(){
            alert(this.attr('x'));
        };
    };
    </script> 
        <div id="holder"></div>
    </body>
    </html>

事件上下文中的"this"对象为您提供DOM节点,而不是围绕它并包含Raphael功能的Element对象。您可以重用创建时声明的上一个Element变量,也可以通过ID:动态检索Element对象

nodeHeader.node.onclick = function(){
    // Re-use previous variable
    alert(nodeHeader.attr("x"));
    // Retrieve dynamically via ID
    alert(paper.getById("nodeHeader").attr("x"));
};

您的问题是将"onClick"处理程序直接放在DOM对象(节点)上,而不是Raphael对象本身。因此,正如Luke所解释的,您在事件处理程序中接收DOM对象作为this指针。如果你把点击处理程序放在拉斐尔对象上,你就会在点击处理程序中收到拉斐尔对象。

试试这个,你会收到你的Raphael对象作为这个指针,正如预期的那样:

nodeHeader.click(function(event) {
    console.log("%o, %o", this, event);
    alert(this.attr('x'));
});