2014-02-28 20 views
-1

我有這個動畫,點擊一個按鈕使div滑動,然後再次下降。它按照我想要的方式工作,但是第一次點擊它時,它不起作用,您必須點擊兩次以獲得響應。使用...如何解決雙擊jQuery上下滑動動畫?

event.preventDefault()和

有人建議event.stopPropagation()

...然而由於我不是與JS很大可能有人建議在那裏我會需要實現這個我現有的代碼來解決問題。

看到下面的小提琴...請注意你必須點擊/點擊兩次才能觸發它我只想點擊一次。

http://jsfiddle.net/8ZFMJ/46/

HTML

<div class="wrapper"> 

<div class="content-wrapper"> 
    <div class="padLeft">  
<h2>Project Title</h2> 
<div class="crossRotate"> Open </div> 
</div>  
<div class="padLeft"> 
<p>Paragraph Goes Here</p> 
<h3>Play Video</h3> 
</div> 
</div>  

</div>  

CSS

.wrapper { 
width: 100%; 
height: 200px; 
position: absolute; 
overflow: hidden; 
margin: 0; 
padding:0; 
z-index: 1; 
} 

.content-wrapper { 
position: absolute; 
z-index: 999; 
background: red; 
bottom: -90px; 
width: 100%; 
-webkit-transition: bottom 1s; 
-moz-transition: bottom 1s; 
transition: bottom 1s;  
} 

.crossRotate { 
position: absolute; 
background-color: blue; 
z-index: 1; 
cursor: pointer; 
} 

JS

var clicked=true, animation=false; 
$(".crossRotate").on('click', function(){ 
if(clicked) 
{ 
clicked=false; 
$(".content-wrapper").css({"bottom": "-90px"}); 
} 
else 
{ 
clicked=true; 
$(".content-wrapper").css({"bottom": "0"}); 
} 
}); 
+2

你的邏輯是相當失敗的,只需設置:'var clicked = false;'http://jsfiddle.net/8ZFMJ/51/ –

+0

啊我看到謝謝你。 – user2498890

回答

4

只要改變點擊

0的初始值
var clicked = false; 
$(".crossRotate").on('click', function() { 
    if (clicked) { 
     clicked = false; 
     $(".content-wrapper").css({ 
      "bottom": "-90px" 
     }); 
    } else { 
     clicked = true; 
     $(".content-wrapper").css({ 
      "bottom": "0" 
     }); 
    } 
}); 

演示:Fiddle

你已經開始爲通過CSS bottom值-90,並點擊設置爲true,所以當第一次點擊的發生,如果塊被執行,而不是別的塊


你或許可以將其降低到

var $wrapper = $(".content-wrapper"); 
$(".crossRotate").on('click', function() { 
    $wrapper.css('bottom', function (i, bottom) { 
     return parseInt(bottom) ? 0 : -90; 
    }); 
}); 

演示:Fiddle

+0

我看到了謝謝,我編輯了一些我在其他方面使用的代碼,並沒有用js很好,所以現在看看我出錯了。非常感謝。 – user2498890

0

如果使用具有特定的類不止一個元素看起來更好:

DEMO jsFiddle

$(".crossRotate").on('click', function() { 
    $(".content-wrapper").css({ 
     "bottom": !$(this).data('clicked') ? 0 : "-90px" 
    }); 
    $(this).data('clicked', !$(this).data('clicked')); 
}); 

甚至更​​好:

DEMO jsFiddle

$(".crossRotate").on('click', function() { 
    $(this).closest('.content-wrapper').toggleClass('clicked'); 
}); 

CSS:

.content-wrapper.clicked { 
    bottom: 0; 
}