动画随机数不运行

Animated random number not running

本文关键字:运行 随机数 动画      更新时间:2023-09-26

我使用了类似post in的代码Jquery中的随机数效果和结果http://jsfiddle.net/ZDsMa/94/…

现在我写完整的代码html和jquery在一个文件php(index.php)和放置在我的服务器…

<html>
<title>Randomize Number</title>
<head>
<style type="text/css">
#output {
    margin: 20px;
    padding: 20px;
    background: gray;
    border-radius: 10px;
    font-size: 80px;
    width: 160px;
    color: red;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script>
var output, started, duration, desired;
// Constants
duration = 5000;
desired = '50';
// Initial setup
output = $('#output');
started = new Date().getTime();
// Animate!
animationTimer = setInterval(function() {
    // If the value is what we want, stop animating
    // or if the duration has been exceeded, stop animating
    if (output.text().trim() === desired || new Date().getTime() - started > duration) {
        console.log('animating');
        // Generate a random string to use for the next animation step
        output.text('' + Math.floor(Math.random() * 990)
        );
    } else {
        console.log('animating');
        // Generate a random string to use for the next animation step
        output.text('' + Math.floor(Math.random() * 990)
        );
    }
}, 1000);
</script>
</head>
<body>
<div id="output">-</div>                    
</body>
</html>

不显示动画随机数(jscript未运行,只有带有'-'字符的框/css)

我的代码有什么问题?

您只需要确保在页面呈现后执行您的代码。试着用:

...
<script>
$( function () {
    var output, started, duration, desired;
    // Constants
    duration = 5000;
    ...
    }, 1000);
});
</script>
...

你可以在这里找到更多信息jQuery.ready().

您需要在$(document).ready()回调中包装与DOM交互的代码:

$(document).ready(function() {
    ...
})

我使用这个javascript代码,它工作

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var output, started, duration, desired;
// Constants
duration = 5000;
desired = '50';
// Initial setup
output = $('#output');
started = new Date().getTime();
// Animate!
animationTimer = setInterval(function() {
    // If the value is what we want, stop animating
    // or if the duration has been exceeded, stop animating
    if (output.text().trim() === desired || new Date().getTime() - started > duration) {
        console.log('animating');
        // Generate a random string to use for the next animation step
        output.text('' + Math.floor(Math.random() * 990)
        );
    } else {
        console.log('animating');
        // Generate a random string to use for the next animation step
        output.text('' + Math.floor(Math.random() * 990)
        );
    }
}, 1000);
})