2012-09-05 47 views
1

我想要實現以下內容:垂直jquery動畫

要點擊的圖像,它將垂直地向上生成一定數量的像素(可以說50)。然後,我想再次點擊它,然後它會回到原來的位置。

我的代碼到目前爲止不起作用。

$("#content").click(function() { 
$("#content").animate(
     {"left": "toggle"}, 
     "slow"); 
}); 

內容在這種情況下只是一個div。我可以做點擊按鈕的簡單教程,它會左右移動div,但是我不能使div成爲按鈕,也不能讓它上下移動。

幫助讚賞,

謝謝。

回答

0

試試這個:

$(function(){ 
var originalHeight = $("#content").height(); 
$("#content").click(function() { 
    var $this = $(this); 
    $("#content").animate(
     {height: ($this.height()==originalHeight ? (originalHeight+50):originalHeight)},  
     "slow"); 
    }); 
}); 

DEMO

希望這會有所幫助。

+0

不幸的是,它沒有做任何事情。 –

+1

@JamesMclaren,這個evnet必須寫在document.ready中。我已經用現場演示更新了我的答案。 –

+0

是的,我已經加入了onload。但是,它只改變了高度。我改變了高度,所以它移動了div而不是改變高度。但是,類似於其他答案,它會將div移到頁面的頂部,這不是我想要的。 –

1

試試這個:

$(document).ready(function() { 
    var up = false; 
    $("#content").click(function() { 
     var newTop = "+=50px"; 
     if (up) { 
      newTop = "-=50px"; 
     }   
     $(this).animate({ top: newTop}, "slow"); 
     up = !up; 
    }); 
}); 

編輯:我添加$(document).ready()上面爲您服務。另請注意,在jsFiddle中查看此動畫時出現的「裸奔」僅限於jsFiddle,並且不會定期發生在頁面上。

祝你好運! :)

+0

如果不清楚,我的變量'up'表示元素是否已經被移動了。對不起,任何混淆 –

+0

類似於之前的迴應。什麼都沒發生。您是否記得添加document.ready? –

+0

? –

2

嘗試以下操作:

HTML

<a href="#" class="moveMe"><img src="..." /><span>Move Me</span>​</a> 

CSS

.moveMe { 
    position: relative; 
    display: block; 
    width: 200px; 
    height: 200px; 
    overflow: hidden; 
} 

.moveMe img { 
    position: absolute; 
    top: 0; 
    left: 0; 
    width: 200px; 
    height: 250px; 
} 

.moveMe span { 
    position: absolute; 
    display: block; 
    bottom: 0; 
    left: 0; 
    padding: 10px 0; 
    width: 100%; 
    color: #fff; 
    text-align: center; 
    background: #000; 
} 

JS

$(document).ready(function(){ 
    var toggled = false; 
    $('.moveMe').bind('click', function(e){ 
     e.preventDefault(); 

     if (toggled){ 
      $('img', this).stop().animate({top: '0'}, 'slow'); 
      toggled = false; 
     } else { 
      $('img', this).stop().animate({top: '-50px'}, 'slow'); 
      toggled = true; 
     } 
    }); 
});​ 

JSFiddle Here

根據需要調整CSS和widthheight

我希望這有助於!