如何点击第二张图片

时间:2013-02-26 12:09:58

标签: javascript

我的网页加载了2个图像和画布。

当页面加载网页时会加载图片。 如果我点击某处,页面会加载画布。

现在我想如果我点击图片就会发生一些事情但是怎么说onclick - >点击图像时。

我想我可以在照片中使用ID。但是在创建图片时如何在javascript中提供iD?

    <script type="text/javascript">
function start() {  
      var vierkant = document.getElementById("Vierkant");  

      initWebGL(vierkant);      // Initialize the GL context  

      // Only continue if WebGL is available and working  

      if (gl) {  
        gl.clearColor(0.0, 0.0, 5.0, 1.0);                      // Set clear color to black, fully opaque  
        gl.enable(gl.DEPTH_TEST);                               // Enable depth testing  
        gl.depthFunc(gl.LEQUAL);                                // Near things obscure far things  
        gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);      // Clear the color as well as the depth buffer.



      }  
    }
function startImage()
{
        var img = document.createElement("img");
        img.src = "Bus_Stop_2.png"; 
        document.body.appendChild( img );
        img.

}


    function initWebGL(vierkant) {  
      // Initialize the global variable gl to null.  
      gl = null;  

      try {  
        // Try to grab the standard context. If it fails, fallback to experimental.  
        gl = vierkant.getContext("webgl") || vierkant.getContext("experimental-webgl");  
      }  
      catch(e) {}  

      // If we don't have a GL context, give up now  
      if (!gl) {  
        alert("Unable to initialize your 'Vierkant'.");  
      }  
    }  

</script>

    <body onclick="start()" onload="startImage()">  
      <canvas id="Vierkant" width="640" height="480">  
        Your browser doesn't appear to support the HTML5 <code>&lt;canvas&gt;</code> element.  
      </canvas>  
</body>

2 个答案:

答案 0 :(得分:0)

创建图片后执行此操作

img.onclick = function() { alert('image clicked') };

你可以代替警报来开展工作!

答案 1 :(得分:0)

这应该有效:

function startImage()
{
        var img = document.createElement("img");
        img.src = "Bus_Stop_2.png"; 
        document.body.appendChild( img );
        img.onclick = function (evt) {
            // do something here
        };
}

要设置ID,您可以使用:img.setAttribute('id', 'myid');

相关问题