查询事件处理程序中的DOM

时间:2012-09-18 06:10:08

标签: javascript events animation dojo

我正在使用DOJO创建一些动画。当鼠标悬停在该区域时,我正试图在一个区域内设置h1的动画。

这确实有效:

HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <script src="//ajax.googleapis.com/ajax/libs/dojo/1.8.0/dojo/dojo.js" data-dojo-config="async: true, isDebug: true"></script>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        <div id="section">
            <div id="title">Something</div>
        </div>
    </body>

</html>

JavaScript的:

require(["dojo/fx", "dojo/on", "dojo/dom", "dojo/mouse","dojo/query","dojo/domReady!"], function(fx, on, dom, mouse,query) {
    var section = dom.byId("section"),
        title = dom.byId("title");

    on(section, mouse.enter, function(evt){
        fx.slideTo({
            node: title, 
            top: "0"
        }).play();
    });

    on(section, mouse.leave, function(evt){
        fx.slideTo({
            node: title, 
            top: "200"
        }).play();
    });
});

我想要工作(但没有):

HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <script src="//ajax.googleapis.com/ajax/libs/dojo/1.8.0/dojo/dojo.js" data-dojo-config="async: true, isDebug: true"></script>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        <section>
            <h1>Something</h1>
        </section>
    </body>

</html>

JavaScript的:

require(["dojo/fx", "dojo/on", "dojo/dom", "dojo/mouse","dojo/query","dojo/domReady!"], function(fx, on, dom, mouse,query) {
    var section = query("section");

    on(section, mouse.enter, function(evt){
        fx.slideTo({
            node: query("h1",this), 
            top: "0"
        }).play();
    });

    on(section, mouse.leave, function(evt){
        fx.slideTo({
            node: query("h1",this), 
            top: "200"
        }).play();
    });
});

我正在尝试使用h1获取query("h1",this)元素来滑动它。我得到的只是我的开发工具中的错误。我试过寻找解决方案,但我找不到。我该如何解决这个问题?

 Uncaught TypeError: Object [object HTMLHeadingElement] has no method 'getBoundingClientRect'

1 个答案:

答案 0 :(得分:1)

问题是query没有返回节点,它返回NodeList。您可以在错误中看到这一点,该错误引用Object [object HTMLHeadingElement] - 这实际上是一个类似于数组的对象(Object [...]),其中包含一个项HTMLHeadingElement

你需要DomNode,所以最简单的解决方案是改变它:

node: query("h1", this)

到此:

node: query("h1", this)[0]

请注意,只有在查询返回有效节点时,此方法才有效。否则,你会得到一个越界错误。

You can see more in the API documentation for dojo/query.