无法调试onmouseover事件

时间:2011-01-15 15:55:52

标签: javascript html

/ *这是monopoly_first_page.html * /

的脚本
var result;
var button;
var image;
var x = 0;

function animation( animatedObject ){

    var hereObject = animatedObject;
    alert( hereObject );

    /*setInterval( animate( animatedObject, x ), 100 );*/

}

function animate( hereObject, x ){

        alert( x );

        if( x == 0){
            hereObject.style.width++;
        }
        else{
            hereObject.style.width--;
        }

        if( hereObject.style.width <= 225 ){
            x = 0;
        }
        if( hereObject.style.width >= 300 ){
            x = 1;
        }
}

function disanimation( animatedObject ){

    var hereObject = animatedObject;
    clearInterval();


}


window.onload = init;

function init(){

    result = document.getElementById( "result" );
    button = document.getElementById( "button-container" );
    document.getElementById( "button-container" ).onmouseclick = animation( button );
    document.getElementById( "button-container" ).onmouseout = disanimation( button );
    alert( button );
    alert( button );

}

嗨每一个......这是我的源代码之一,我是一个初学者...我遇到了一个问题,这是我写这个声明的地方:

document.getElementById( "button-container" ).onmouseclick = animation( button );

当函数init开始运行时,函数动画也会强制执行...但我确定我不会将鼠标滚动到指定的DIV上... 有什么问题?

3 个答案:

答案 0 :(得分:2)

您需要将函数传递给任何处理程序。您的代码发生的是它调用animation(button)然后将该值设置为onmouseclick属性。由于animation(...)函数不返回函数,因此不会发生任何有益的事情。

这将更加接近。

whatever.onmouseclick = animation;  

如果需要,您也可以这样做:(假设您想要传递特定按钮)

whatever.onmouseclick = function(e) { animation(button); }

答案 1 :(得分:0)

只想添加到约翰,你也可以做

document.getElementById( "button-container" ).addEventListener("click",function(){animation(button);},true);

而不是“onmouseclick”

: - )

答案 2 :(得分:0)

正如@JohnFisher已经提到的,您将函数的RESULT分配给事件 但是我只使用onclick。你从哪里得到onmouseclick? 另外,你不必要地重复你的getElementById,并有一个onload是一个onload,所以巩固它:

window.onload = function() {
  var button = document.getElementById( "button-container" );
// button is not necessarily known or the same at the time of the click so use (this)
  button.onclick = function() { animation(this); }
  button.onmouseout = function() { disanimation(this); }
}