jquery .animate在jsfiddle中工作,不能在网站上工作

时间:2014-02-19 08:08:05

标签: javascript jquery

我正在尝试将这个简单的jquery code实现到我的网站中,我无法使其正常工作!

这是完整的HTML代码(一切都与WORKING jsfiddle版本相同,但它不起作用):

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>

<script src="js/jquery-1.9.0.min.js"></script>

<style>
    div#test {
        background: #b977d1;
        margin: 3px;
        width: 150px;
        height: 20px;
        float: right;
        display: none;
        overflow:hidden;
    }
    button#aa {
        float: right;
    }
</style>

</head>

<body>

<script type="text/javascript">
$("#aa").click(function () {
    $("div#test").animate({
        width: 'toggle'
    });;
});

</script>

<div id="test">TEST das das dsa</div>
<button id="aa">Toggle</button>
</body>
</html>

我对此感到非常沮丧:P

如果有人能帮助我,我会非常感激! :)

3 个答案:

答案 0 :(得分:1)

将您的jquery包含在$(document).ready() jsfiddle中,自动执行此操作 试试这个:

$(document).ready(funciton(){
    $("#aa").click(function () {
        $("div#test").animate({
            width: 'toggle'
        });;
    });
});

答案 1 :(得分:1)

您需要将代码包装在DOM ready处理程序中,以确保文档对象模型(DOM)已准备好执行JavaScript代码。

当您包含jQuery库时,jsFiddle会自动完成此步骤。

$(function(){
    $("#aa").click(function () {
        $("div#test").animate({
            width: 'toggle'
        });;
    });
});

如果您希望在整个页面(图片或iframe)(而不仅仅是DOM)准备就绪后运行代码,请将代码放入$(window).load(function() { ... })

$(window).load(function() { 
    $("#aa").click(function () {
        $("div#test").animate({
            width: 'toggle'
        });;
    });
})

答案 2 :(得分:1)

您需要在ready函数的回调中设置jQuery代码。

$(function() {
 // when the document is ready
 // here, your code
});