[英]What is wrong with my jQuery code?
當有人單擊浮動在右邊的h1時,我想從左向右切換div,每件事都工作正常,但我無法切換。 一旦div出現,它就永遠不會消失。
<script>
$(document).ready( function (){
/*
THIS COMMENTED SECTION IS WORKING BUT WITHOUT TOGGLE
$('h1').click(function (e){
e.preventDefault();
$('div').animate({
'left': 0
}, 'slow');
});
*/
// This is not working!
$("h1").click(function(){
$("div").toggle(function() {
$("div").animate({'left': '-32%'});
}, function() {
$("div").animate({height: '0'});
});
});
});
</script>
和HTML:
<h1>Click here!</h1>
<div style="left: -32%; display: block;">Put whatever content you want here!
<ul>
<li>CLICK ON THE LINK</li>
<li>CLICK ON THE LINK</li>
<li>CLICK ON THE LINK</li>
<li>CLICK ON THE LINK</li>
</ul>
</div>
.toggle()
多功能參數形式已在jQuery 1.8中棄用,在1.9中已刪除,並且具有內置的單擊處理程序。 因此,它無法像您嘗試使用它的方式那樣起作用,並且不再受支持。
這是.toggle()
多功能版本的替代品:
jQuery.fn.cycleFunctions = function() {
var args = Array.prototype.slice.call(arguments);
// initialize index into function arguments
var indexTag = "_cycleIndex";
this.data(indexTag, 0);
this.on("click", function(e) {
var self = $(this);
var index = self.data(indexTag) % args.length;
self.data(indexTag, index + 1);
return args[index].call(this, e);
});
return this;
};
請注意,這已經為您完成了.click()
處理程序,因此您無需將其放在點擊處理程序中。
因此,結合您的代碼:
<h1>Click here!</h1>
<div class="toggle" style="left: -32%; display: block;">Put whatever content you want here!
<ul>
<li>CLICK ON THE LINK</li>
<li>CLICK ON THE LINK</li>
<li>CLICK ON THE LINK</li>
<li>CLICK ON THE LINK</li>
</ul>
</div>
// This works with two operations that are opposites of each other
// which your two animations are not
$("h1").cycleFunctions(function(){
$(this).next(".toggle").slideUp();
}, function() {
$(this).next(".toggle").slideDown();
});
然后,您必須將CSS修復為兩個動作是可逆的。 為了向左移動樣式,該項目必須具有非默認的位置樣式設置。 並且,一旦發生第二次單擊並且該項目的高度為零,該項目將永遠不會再次可見,因此可以兩次單擊就可以再次看到。
這是一個工作示例: http : //jsfiddle.net/jfriend00/Xj65L/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.