jquery animate不起作用

时间:2013-04-01 05:41:44

标签: javascript jquery html

嗨我有一个带有以下代码的简单滑块:

HTML代码:

<div id="gallery">
    <a href="#" id="left-arrow">..</a>
    <a href="#" id="right-arrow">..</a>
    <div id="container">
        <div class="item">...</div>
        <div class="item">...</div>
        ...
        <div class="clr"></div>
    </div>
</div>

CSS样式:

#gallery {
    position:relative;
    width:290px;
    height:200px;
    overflow:hidden;
}
#gallery #container{
    position:absolute;
    left:0px;
    top:0px;
    width:1160px;
}
#right-arrow, #left-arrow{
    width:30px;
    height:30px;
    position:absolute;
    top:85px;
    z-index:200;
}
#right-arrow{
    right:10px;
}
#left-arrow{
    left:10px;
}

JS代码:

    <script type="text/javascript">
    $(document).ready(function(){
// I must set left position explicitly if not when fetching left position it returns "auto"
// I used position.left property, however. but It doesn't returns left relative 
// to parent insted (I think) relative to document which (I don't know why? It is not 
// according to Jquery documentation which position.left - .offset() is relative to document)
        $('#container').css('left', '0px'); 
        $('#right-arrow').click(function(){
            move('right');
        });
        $('#left-arrow').click(function(){
            move('left');
        })

        move = function (direction){
                .
                . 
                .
            // The problem is here:
                $('#container').animate(left:'+=290');

                // although setting it's css left position doesnt work
                $('#container').css('left', '290px');

                // I return container to use it in console!
                return $(#container');
        }
    });
    </script>

我用console来调试它我发现它正确地将css位置设置为我想要的但实际上它不起作用 看看:

控制台:

>>> var x = move()
Object[div#container]

>>> x.css('left', '1000px')
Object[div#container]

>>> x.css('left')
"1000px"
// But It doesn't move in reality 

我讨厌Javascript,请帮帮我,我不知道是什么问题

2 个答案:

答案 0 :(得分:4)

要使topleftbottomright css规则有效,您需要将position css规则添加到dom

div
{
   top:10px;
   left:10px;
}

上面的代码不会将顶部和左侧应用于div,而是

div
{
   top:10px;
   left:10px;
   position : relative;//absolute or fixed or etc
}

上面的代码可以使用。

您有以下错误。

return $(#container'); 替换为 return $('#container');

替换 .animate(left:'+=290'); .animate({left:'+=290'});

答案 1 :(得分:2)

天啊,我发现了问题。问题不在于我的代码。另一个元素是另一个地方,ID为'container',它位于第三方模块中 对不起伙计我的错!! :d