我只是在尝试使用Javascript库来创建一些简单的矢量图形。应该有一个正方形对象和一个弯曲对象,但没有显示任何内容。有人能帮我吗。谢谢。
<html>
<head>
<script src="raphael.js"></script>
<script src="jquery-1.7.2.js"></script>
<script type="text/javascript"> //all your javascript goes here
var paper = Raphael("sample-2", 200, 100);
var rectPath = paper.path("M10,10L10,90L90,90L90,10Z");
var curvePath = paper.path("M110,10s55,25 40,80Z");
rectPath.attr({fill:"green"});
curvePath.attr({fill:"blue"});
</script>
</head>
<body>
<div id="sample-2" style="width:500px; height:500px;">
</div>
</body>
</html>发布于 2012-07-18 03:46:35
您运行Javascript的时间太早了。您的浏览器将在读取Javascript时运行它,如果DOM元素尚未加载,它将不会执行任何操作。
试试这个:
<html>
<head>
<script src="raphael.js"></script>
<script src="jquery-1.7.2.js"></script>
</head>
<body>
<div id="sample-2" style="width:500px; height:500px;"></div>
<script type="text/javascript">
//all your javascript goes here
var paper = Raphael("sample-2", 200, 100);
var rectPath = paper.path("M10,10L10,90L90,90L90,10Z");
var curvePath = paper.path("M110,10s55,25 40,80Z");
rectPath.attr({
fill: "green"
});
curvePath.attr({
fill: "blue"
});
</script>
</body>
</html>祝你愉快,祝你好运!
发布于 2012-07-18 03:44:41
将脚本移到<div id="sample-2" style="width:500px; height:500px;">标记之后
或者有些人更喜欢使用onload处理程序,为了简单起见,使用jQuery
$(function(){
// Your code that runs after the DOM is loaded
});关键是您的代码正在访问DOM,并且它需要在构建DOM之后运行。从onload处理程序或在您正在使用的DIV之后调用它可以确保元素已经准备好与之交互。
发布于 2012-07-18 05:38:03
@JuanMendes这有点令人困惑,最终的问题是js函数在DOM准备好之前就被调用了,elemets还在创建中。我建议使用$(document).ready(function(){}),以便只有在创建了DOM之后才会执行脚本。我只是再解释一次,因为他问他为什么要这样做。例如,如果他这样做了:
<html>
<head>
<script src="raphael.js"></script>
<script src="jquery-1.7.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){ //all your javascript goes here
var paper = Raphael("sample-2", 200, 100);
var rectPath = paper.path("M10,10L10,90L90,90L90,10Z");
var curvePath = paper.path("M110,10s55,25 40,80Z");
rectPath.attr({fill:"green"});
curvePath.attr({fill:"blue"});
}
)
</script>
</head>
<body>
<div id="sample-2" style="width:500px; height:500px;">
</div>
</body>
</html>该脚本应该可以工作,因为脚本是在DOM准备好之后执行的。
附注:如果你想操纵动态创建的内容,你需要在点击、模糊、悬停等操作时附加事件处理函数。绑定操作,以便注册该事件。示例:
$('#form').on('blur', '#input', function(){
// code
})您可以在:http://api.jquery.com/on/和.ready()的:http://api.jquery.com/ready/上查看绑定文档
https://stackoverflow.com/questions/11529750
复制相似问题