尝试在单击时移动图像,但是 .click 甚至仅在第一次单击时触发

Trying to make an image move whenever clicked, however the .click even only fires the first time clicked

本文关键字:单击 第一次 移动 图像 但是 click      更新时间:2023-09-26

我正在尝试让图像(#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)
});

工作示例

演示