动画随机数未运行

时间:2013-03-22 04:24:22

标签: javascript jquery html

我使用了像post这样的代码 Random Number Effect In Jquery .. 和结果http://jsfiddle.net/ZDsMa/94/ ......

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

<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未运行,只有' - 'characher / css的框)

我的代码出了什么问题?

3 个答案:

答案 0 :(得分:1)

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

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

    ...

    }, 1000);
});
</script>
...

您可以在jQuery.ready()找到更多信息。

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

嗨使用这个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);
})