2013-04-01 66 views
1

您好我有一個簡單的滑塊與此代碼:jQuery的動畫不起作用

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> 

我用控制檯來調試它我發現我牛逼正確地設置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,請幫助我,我不知道是什麼問題

+4

_「我討厭Javascript」_ - 我笑了一下。 –

回答

2

哦,我的上帝,我發現這個問題。問題不在我的代碼中。還有另一個地方的ID爲'container'另一個地方它在第三方模塊 抱歉,傢伙我的錯! :D

4

爲了topleftbottomright CSS規則來工作,你需要position CSS規則添加到dom

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

上面的代碼將不適用頂部和左格但

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

上面的代碼將正常工作。

您有以下錯誤。

更換return $(#container');return $('#container');

而且更換.animate(left:'+=290');.animate({left:'+=290'});

+0

我設置了頂部,並明確地在css規則中留下了 –

+0

@MustafaShujaie還添加了'position:relative',並且看到我相信這會起作用。 –

+0

@Dispeh看到css #gallery #container –