使用JQuery在鼠标点击上插入圆圈
Inserting circles on mouse click using JQuery
今天刚开始学习这门语言(如果这是一个愚蠢的问题,我很抱歉),但我正试图弄清楚如何在网页上插入圆圈。我在这里找到了一个示例代码:http://jsfiddle.net/7xQZ2/但是,当我尝试从单个文件运行它时,脚本部分由于某种原因没有运行。我试着改变周围的<body>
和<script>
。它只是显示一个坐标为(0,0)的框。它保持静态,当我移动鼠标时它不会改变。
<!DOCTYPE html>
<html>
<head>
<h2 id="status2">0, 0</h2>
<canvas width="500px" height="500px" style="width: 500px; height: 500px; border:1px ridge green;" id="special">
</canvas>
</head>
<body>
<script>
jQuery(document).ready(function(){
$("#special").click(function(e){
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
/* var c=document.getElementById("special"); */
var ctx= this.getContext("2d"); /*c.getContext("2d");*/
ctx.beginPath();
ctx.arc(x, y, 10,0, 2*Math.PI);
ctx.stroke();
$('#status2').html(x +', '+ y);
});
})
</script>
</body>
</html>
您需要包含jQuery。将这行放在head
部分:
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
同时将head
中的位置移动到body
中,反之亦然。
您的代码正在使用jQuery库。请确保在使用代码之前包含它。
另外,所有的HTML元素都需要在body标签中,而不是head标签中。
<!DOCTYPE html>
<html>
<body>
<h2 id="status2">0, 0</h2>
<canvas width="500px" height="500px" style="width: 500px; height: 500px; border:1px ridge green;" id="special">
</canvas>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
jQuery(document).ready(function(){
$("#special").click(function(e){
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
/* var c=document.getElementById("special"); */
var ctx= this.getContext("2d"); /*c.getContext("2d");*/
ctx.beginPath();
ctx.arc(x, y, 10,0, 2*Math.PI);
ctx.stroke();
$('#status2').html(x +', '+ y);
});
})
</script>
</body>
</html>
如果你的HTML只有这个
<!DOCTYPE html>
<html>
<head>
<h2 id="status2">0, 0</h2>
<canvas width="500px" height="500px" style="width: 500px; height: 500px; border:1px ridge green;" id="special">
</canvas>
</head>
<body>
<script>
jQuery(document).ready(function(){
$("#special").click(function(e){
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
/* var c=document.getElementById("special"); */
var ctx= this.getContext("2d"); /*c.getContext("2d");*/
ctx.beginPath();
ctx.arc(x, y, 10,0, 2*Math.PI);
ctx.stroke();
$('#status2').html(x +', '+ y);
});
})
</script>
</body>
</html>
那么是的,它不起作用。因为你使用的代码属于JavaScript的jQuery库。这需要在代码中包含jQuery。它不是每个浏览器内置的。
使用此代码添加它。
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
相关文章:
- 如何动态插入jquery代码
- 换行符插入jquery选择器
- 将方法插入jQuery插件
- 在另一个脚本后插入Jquery
- 我应该如何在提交操作之前插入jQuery代码
- 创建 var 并将其插入 jQuery Child Selector(“父>子”)
- 如何在页脚中插入 jQuery 时定义变量
- 阻止第三方JavaScript插入jQuery
- 如何将HTML文本插入jQuery
- 如何将PHP插入jQuery
- 通过PHP在MySQL中插入Jquery
- 如何在PHP代码中插入jQuery插件?
- 在DOM中插入jQuery验证代码
- 使用userscript在header中插入jQuery和jQuery UI
- 在对象id:中插入jquery字符串
- 在表模板中插入jQuery输入
- Jquery插入Jquery属性
- 在带有事件的另一个浏览器选项卡中插入jQuery对象
- 如何在php数组中插入jquery值
- 难以将变量插入jquery属性标识