我想将动态图像的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>
答案 0 :(得分:1)
你确定这个:
var avatar = document.getElementsByName(id);
不应该是:
var avatar = document.getElementById(id);
getElementsByName
方法将返回元素的HTMLCollection,您可以这样访问:
avatar[0].textContent = "Yay, I'm the first matched item";
答案 1 :(得分: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";
}
}
答案 2 :(得分:0)
使用
document.getElementById(id)
而不是
document.getElementsByName(id)
link:https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById