使用 JavaScript 在特定距离处创建图像
function on_click(e)
{
if( !e ) e = window.event;
dragok = false;
document.onmousemove = null;
var x = e.target||e.srcElement;
if( dx > 200 ) // dx is the numbers of pixels from leftside of mouse pointer
{
// document.write(dx); this is working it prints dx value but unable to create an image
var img = IEWIN ? new Image() : document.createElement('img');
img.src="cool.jpg";
document.getElementById(x.id).appendChild(img);
}
}
我在 Stack Overflow 上找到了这些片段,但在尝试时不起作用。这是 什么是最好的 JavaScript 代码创建一个 img 元素。
目的是在调用函数 on_click 时创建图像(为 onclick
事件调用函数 on_click
)。 dx
是从左侧测量的像素。因此,如果鼠标指针大于 200 像素并且单击鼠标,它应该在该位置创建一个图像我的意思是如果 dx 是 206,那么应该创建一个距离为 206 像素的图像,但我无法使用 JavaScript 创建图像元素。
我必须在 JavaScript 代码中进行哪些更改?
function on_click(e)
{
if( !e ) e = window.event;
dragok = false;
document.onmousemove = null;
var x = e.target||e.srcElement;
if( dx > 200 ) // dx is the numbers of pixels from leftside of mouse pointer
{
// document.write(dx); this is working it prints dx value but unable to create an image
var img = IEWIN ? new Image() : document.createElement('img');
img.src="cool.jpg";
document.getElementById(x.id).appendChild(img);
}
}
I found these snippet on Stack Overflow but not working when I tried it . Here it is What is the best JavaScript code to create an img element.
The aim is to create an image when function on_click is called, (function on_click
is called for onclick
event). dx
is the pixels measured from the left side. So if the Mouse pointer is greater than 200 pixels and if the mouse is clicked, It should create an image at that place I mean if dx
is 206 then an image should be created with the distance of 206 pixels, but I'm unable to make create an image element with JavaScript.
What changes I have to make in JavaScript code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于所有浏览器,您所需要的只是这样:
如果您已经拥有 DOM 元素,则没有理由获取 id,然后执行
document.getElementById(x.id)
。直接使用x
即可。要使用引用该图像的 CSS 规则,您可以制定如下规则(取决于您引用的是类还是 id):
All you need is this for all browsers:
If you already have the DOM element, there's no reason to get the id and then do
document.getElementById(x.id)
. Just usex
directly.To use CSS rules that refer to this image, you would make rules like this (depending upon whether you're referring to the class or the id):