开发者

Create an image using JavaScript at a particular distance

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 calle开发者_开发知识库d 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?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜