[英]Expand on click, collapse on click outside
我有一個元素,我想在點擊上展開,然后在外面點擊折疊,從而得到以下代碼。 然而,當我運行它時,它將開始擴展然后立即崩潰,因為兩個函數都是按順序調用的。 我不明白為什么以及如何解決這個問題。
jQuery(document).ready(function() {
var element = jQuery("#search-main");
var defaultWidth = jQuery("#search-main").css('width');
var expandWidth = "200px";
var fnSearch = {
expand : function() {
jQuery(element).animate({
width : expandWidth
});
jQuery(document).bind('click', fnSearch.collapse);
},
collapse : function() {
jQuery(element).animate({
width : defaultWidth
});
event.stopPropagation();
jQuery(document).unbind("click", fnSearch.collapse);
}
}
jQuery("#search-main").bind("click", fnSearch.expand);
});
您遇到了問題,因為#search-main
click事件正在傳播到文檔; 即首先觸發#search-main
click事件,然后觸發document
點擊事件。 Click事件默認執行此操作。 要停止此事件傳播,您需要在expand
功能中使用http://api.jquery.com/event.stoppropagation/ :
jQuery(document).ready(function() {
var element = jQuery("#search-main");
var defaultWidth = jQuery("#search-main").css('width');
var expandWidth = "200px";
var fnSearch = {
expand : function(event) { // add event parameter to function
// add this call:
event.stopPropagation();
jQuery(element).animate({
width : expandWidth
});
jQuery(document).bind('click', fnSearch.collapse);
},
collapse : function() {
jQuery(element).animate({
width : defaultWidth
});
jQuery(document).unbind("click", fnSearch.collapse);
}
}
jQuery("#search-main").bind("click", fnSearch.expand);
});
也就是說,Jason P的解決方案更適合您的需求。 它更可靠,更簡潔,因為您不必將document
綁定到document
,如果您習慣性地使用該策略,這很容易變得難以跟蹤並導致與其他代碼沖突。
單擊后可以從#search-main
元素取消綁定click事件,或者停止事件的傳播,但我建議綁定到blur和focus事件:
(function ($) {
$(document).ready(function () {
var element = jQuery("#search-main");
var defaultWidth = jQuery("#search-main").css('width');
var expandWidth = "200px";
$('#search-main').on('focus', function () {
$(element).animate({
width: expandWidth
});
}).on('blur', function () {
$(element).animate({
width: defaultWidth
});
});
});
})(jQuery);
這樣,即使用戶選擇進入或離開字段,它也會起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.