【问题标题】:jquery .animate works in jsfidle, will not work in website [duplicate]jquery .animate 在 jsfidle 中有效,在网站中无效 [重复]
【发布时间】:2014-02-19 16:16:13
【问题描述】:

我正在尝试在我的网站中实现这个简单的 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

如果有人能帮我解决这个问题,我将不胜感激! :)

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

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

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

    【讨论】:

    • 哇!有用! 1 分钟后准备好解决方案.. 我花了 1 个小时来解决它,但无法解决!非常感谢!!!
    • 很高兴为您提供帮助!提醒接受答案以帮助其他人解决同样的问题@user3327001
    【解决方案2】:

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

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

    【讨论】:

    • 感谢您提供有效的解决方案! :)
    【解决方案3】:

    您需要将代码包装在 DOM 就绪处理程序中,以确保文档对象模型 (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'
            });;
        });
    })
    

    【讨论】:

    • 非常感谢您的努力!一切都很好,我也知道将来该怎么做!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多