如何将图像 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
相关文章:
- 我应该如何从xml文件构建一个javascript页面
- Javascript页面调用函数
- 当同一浏览器的两个实例浏览时,Javascript页面如何具有唯一的ID
- javascript页面加载发生在Button Click上
- 从Ajax脚本重定向Javascript页面
- 如何在不更改Javascript页面的情况下访问用户输入的电子邮件
- ajax html javascript页面刷新无闪烁问题
- 将按钮名称和值传递给另一个 JavaScript 页面
- javascript页面加载检查是否存在具有特定类的span(在<tr>下),如果不存在,则删除整个<
- 如何在PHP中包含动态Javascript页面的静态HTML结果
- Javascript 页面擦除过渡与超级滚动
- JavaScript 页面未正确重定向
- 简单的JavaScript页面按钮导航
- Javascript 页面过渡未定义
- Javascript 页面呈现为文本,而不是执行 document.location
- 我如何创建一个简单的javascript页面,允许用户输入文本并显示它
- JavaScript页面加载位置
- Javascript 页面重置
- 如何将图像 ID 传递给 JavaScript 页面
- 如何对内容名称由引用定义的 JavaScript 页面进行爬网