如何将图像 ID 传递给 JavaScript 页面


how to pass image id to javascript page

我想将动态图像的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>

你确定这样吗:

var avatar = document.getElementsByName(id);

不应该是:

var avatar = document.getElementById(id);

getElementsByName 方法将返回元素的 HTMLCollection,您可以像这样访问该元素:

avatar[0].textContent = "Yay, I'm the first matched item";

你真正需要的是:

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"; 
    }
}

使用

     document.getElementById(id)

而不是

     document.getElementsByName(id)

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