3

我无法使用 jquery 访问画布 ID。

我添加了 jQuery 库。但是当我单击画布 ID 时,我无法收到警报。

但是javascript工作正常。

    <script>
    $(document).ready(function(){
    $('#sq').click(function(){
    alert('test');
    });
    });
    </script>
    <canvas id="example" width="260" height="200">
        <h2>Shapes</h2>
      <p>A rectangle with a black border. In the background is a pink circle. Partially overlaying the 
      <a href="http://en.wikipedia.org/wiki/Circle" onfocus="drawCircle();" onblur="drawPicture();">circle</a>. 
      Partially overlaying the circle is a green 
      <a href="http://en.wikipedia.org/wiki/Square" onfocus="drawSquare();" onblur="drawPicture();" id="sq">square</a> 
      and a purple <a href="http://en.wikipedia.org/wiki/Triangle" onfocus="drawTriangle();" onblur="drawPicture();">triangle</a>, 
      both of which are semi-opaque, so the full circle can be seen underneath.</p>
    </canvas>​
4

3 回答 3

3

您放入canvas元素中的所有内容都是后备内容:它不会在现代浏览器中使用,因此您无法访问它,当然也无法单击它。

canvas在现代浏览器中正确使用 a是使用它的context.

来自MDN

<canvas> 元素是一个 HTML 元素,可用于通过脚本(通常是 JavaScript)绘制图形。例如,它可用于绘制图形、制作照片合成、创建动画甚至进行实时视频处理。

如果您想捕捉点击canvas,请执行

$('#example').click(function(){ // <-- use the id of the canvas
    alert('test');
});
于 2012-11-08T10:48:21.063 回答
1

您不应该将 html 元素放在 canvas 标记内。画布的想法是使用代码(也称为 javascript)在其上绘制。你正在做的事情是行不通的(或者只有在浏览器不支持画布时才会看到 - 这意味着非常非常旧的浏览器):)

于 2012-11-08T10:48:27.380 回答
1

将 html 元素从画布中取出并更改$('#sq').click(function(){$('#example').click(function(){

看看这个:http: //jsfiddle.net/Zprb4/

于 2012-11-08T10:50:21.810 回答