使用 JavaScript 在特定距离处创建图像

发布于 2024-12-05 07:19:49 字数 953 浏览 3 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

从﹋此江山别 2024-12-12 07:19:49

对于所有浏览器,您所需要的只是这样:

var img = new Image();
img.src = "cool.jpg";
img.className = "myClass";
img.id = "mainImage";
x.appendChild(img);

如果您已经拥有 DOM 元素,则没有理由获取 id,然后执行 document.getElementById(x.id)。直接使用x即可。

要使用引用该图像的 CSS 规则,您可以制定如下规则(取决于您引用的是类还是 id):

.myClass {border: 1px solid #F00;}
#mainImage {padding: 14px;}

All you need is this for all browsers:

var img = new Image();
img.src = "cool.jpg";
img.className = "myClass";
img.id = "mainImage";
x.appendChild(img);

If you already have the DOM element, there's no reason to get the id and then do document.getElementById(x.id). Just use x 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):

.myClass {border: 1px solid #F00;}
#mainImage {padding: 14px;}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文