概念 - “this”在addEventListener回调中引用了什么?

时间:2012-05-31 18:46:13

标签: javascript

此功能不起作用..无法找出原因......没有错误......但单击时图像不会缩小。

image_element.addEventListener( "click", function( )
{ 
    this.style.width = ( parseInt( this.style.width ) - 1 ) + 'px';
    this.style.height = ( parseInt( this.style.height ) - 1 ) + 'px';
}, false );

4 个答案:

答案 0 :(得分:2)

this,在eventListener的上下文中,是[引发事件]的元素。您可能遇到的一个问题是,this.style.width可能尚未指定...

记录/提醒this.style.width的值,并首先查看其中的内容。

答案 1 :(得分:1)

image_element.addEventListener( "click", function( )
{ 
    var iWidth  = parseInt(this.style.width.substr(0, this.style.width.length-2), 10);
    var iHeight = parseInt(this.style.height.substr(0, this.style.height.length-2), 10);

    this.style.width  = (parseInt(iWidth  - 1, 10)) + 'px';
    this.style.height = (parseInt(iHeight - 1, 10)) + 'px';
}, false );

答案 2 :(得分:1)

关键字this是指触发事件的人,在这种情况下是DOM Element

但是您的问题是因为样式为undefined而您没有初始化它。因此,即使您尚未初始化它,也应该使用“ComputedStyle”来获取当前值。

image_element.addEventListener( "click", function( )
{ 
    this.style.width = ( getStyle(this,'width',true) - 1 ) + 'px';
    this.style.height = ( getStyle(this,'height',true) - 1  ) + 'px';
}, false );

将此功能附加到您的文档:

/** Get the current computed style of an element */
function getStyle(element, strCssRule, returnInt){
    if(typeof element==="string"){element=document.getElementById(element);}
    var strValue = "";
    if(document.defaultView && document.defaultView.getComputedStyle){
        strValue = document.defaultView.getComputedStyle(element, "").getPropertyValue(strCssRule);
    }
    else if(element.currentStyle){
        strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){ return p1.toUpperCase(); });
        strValue = element.currentStyle[strCssRule];
    }
    if(returnInt===true){ strValue=parseInt(strValue); }
    return strValue;
}

答案 3 :(得分:-1)

使用jQuery:

function initOrbs()
{
    var image_element = document.createElement( 'img' );
        $(image_element).addClass("orb");
        image_element.id = icon_array[ initOrbs.index ];
        image_element.speed = icon_array[ initOrbs.index + 1 ];
        if(image_element.speed  > 10000 )
        {
            image_element.speed  = image_element.speed / 10;
            $(image_element).width(20);
            $(image_element).height(20);
        }
        image_element.src = '/develop/foo/favicons/' + icon_array[ initOrbs.index ];  
        image_element.style.top = '-80px';
        image_element.style.left = random( 100, 800) + 'px';
        sky.appendChild( image_element );
        $(image_element).click( function()
        { 
            $(this).width( parseInt( $(this).width() ) - 1 );
            $(this).height( parseInt( $(this).height() ) - 1 );
        });
        moveLinear( image_element );
        initOrbs.index += 2;
}