0

我想将动态图像的 id 传递给 javascript 函数,但总是得到 null 或 [ObjectHTMLElement]。

这是我的代码:

function image_select(id) {  
    document.onmousemove=function(e) {
        var avatar = document.getElementsById(id);
        avatar.style.position='relative';
        avatar.style.left = Math.min(Math.max(e.x-530,-25 ),25)+ "px";
        avatar.style.top = Math.max(Math.min(e.y-256,90),-8) + "px";    
    }
}

function onup(id) {
    document.onmouseup=function() {
        document.getElementById(id).style.position='relative';
        document.onmousemove=null
    }
}


<div id="<?php echo $line4->id."back"; ?>" style="background-image:url(images/fp1.jpg);background-size:100%; padding:0px; margin:0px; background-repeat:no-repeat; border:thin solid black; width:130px; height:130px;" >

    <img name="<?php echo $line->id ?>" src="<?php echo "admin/files/".$line4->image_path3; ?>" 
            style="z-index:1; opacity:.4;" 
            onMouseDown="image_select(<?php echo $line->id ?>);" 
            onMouseUp="onup(<?php echo $line->id ?>);" />
</div>
4

3 回答 3

1

你确定这是:

var avatar = document.getElementsByName(id);

不应该是:

var avatar = document.getElementById(id);

getElementsByName方法将返回一个 HTMLCollection 元素,您可以像这样访问它:

avatar[0].textContent = "Yay, I'm the first matched item";
于 2013-09-26T16:55:40.350 回答
0

你真正需要的是:

onMouseDown="image_select(this);"

function image_select(obj) {
    document.onmousemove=function(e) {
       obj.style.position='relative';
       obj.style.left = Math.min(Math.max(e.x-530,-25 ),25)+ "px";
       obj.style.top = Math.max(Math.min(e.y-256,90),-8) + "px"; 
    }
}
于 2013-09-26T16:58:03.910 回答
0

使用

     document.getElementById(id)

代替

     document.getElementsByName(id)

链接:https ://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById

于 2013-09-26T17:00:30.183 回答