尝试在单击时移动图像,但是 .click 甚至仅在第一次单击时触发
Trying to make an image move whenever clicked, however the .click even only fires the first time clicked
我正在尝试让图像(#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>
如果这是一个愚蠢的问题,我深表歉意,但我对 Web 开发仍然相当陌生。
您的随机值仅在脚本开始时计算一次。每次单击时,您的元素都会以完全相同的值进行动画处理,效果仅在第一次显示。
您应该在每次点击时创建新值。
$(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)
})
});
HTML
<div id = "goondiv">
<img src = "goon.jpg" id = "goon"/>
</div>
.JS
var random = 750;
var random2 = 200;
$("#goon").click(function move() {
random = Math.floor(Math.random()* 750 + 1)
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)
});
工作示例
演示
相关文章:
- 当单击第一个李时,它显示内容一,当单击第二个李时,它显示内容二
- 单击一次后禁用按钮-第2部分
- 如何对每个用户每天只允许单击一次的按钮进行编码
- button.单击两次删除附加操作后不工作
- 为什么jQuery下拉列表需要单击两次
- 单击3次后禁用按钮
- 为什么在文本框内按回车键,单击第一个按钮并提交表单
- 为每个字母单击一次
- Rails-jQuery 为什么我必须单击两次才能显示 jQuery 效果
- 对同一类中的所有元素单击一次
- 单击一次以静音,另一次单击可取消静音
- 必须单击两次才能得到一个响应
- 如何在幻灯片中添加向上滚动功能单击1次即可向下滚动
- 如何加载一个html页面并在其中只需单击一次即可运行函数
- Javascript:表单在第一次验证和应用样式后提交
- 页面加载后的第一个锚定链接需要单击两次
- 在同一元素上单击两次,然后在另一个元素上单击两次,使第一个元素进入“单击”状态
- JavaScript单击事件只在InfoPath表单上第一次触发
- Ajax + JSF在第一次单击后单击2次
- 表单在第一次单击后N秒自动提交