我试图让图像(#goon)移动并在单击时调整大小。该代码运行良好,但仅在第一次单击时有效。第一次单击图像后,单击图像不会执行任何操作。
这是 JavaScript 代码:
var random = Math.floor(Math.random()* 750 + 1)
var random2 = Math.floor(Math.random() * 200 + 10)
$(document).ready(function() {
$("#goon").click(function move() {
$("#goon").animate({left: random},0)
$("#goon").animate({top: random},0)
$("#goon").animate({height: random2},0)
$("#goon").animate({width: random2},0)
})
});
这是 HTML 代码:
<!DOCTYPE html>
<html>
<head>
<title>Goon</title>
<link rel='stylesheet' href='style.css' type = "text/css"/>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.2/jquery-ui.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id = "goondiv">
<img src = "goon.jpg" id = "goon"/>
</div>
</body>
</html>
如果这是一个愚蠢的问题,我真诚地道歉,但我对网络开发仍然相当陌生。
最佳答案
您的随机值仅在脚本开始时计算一次。每次点击时,您的元素都会动画化为完全相同的值,效果仅在第一次显示。
您应该在每次点击时创建新值。
$(document).ready(function() {
$("#goon").click(function move() {
var random = Math.floor(Math.random()* 750 + 1)
var random2 = Math.floor(Math.random() * 200 + 10)
$("#goon").animate({left: random},0)
$("#goon").animate({top: random},0)
$("#goon").animate({height: random2},0)
$("#goon").animate({width: random2},0)
})
});
关于javascript - 尝试让图像在单击时移动,但是 .click 甚至只在第一次单击时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27772697/