我是jQuery的新手,我尽力将一个函数放在一起,点击打开一个对话框消息,然后点击再次关闭它。我想要的是能够在对话框外(屏幕上的任何位置)单击以关闭该对话框。我怎么能在我写的设置中完成这个?此外,我目前正确完成的代码,还是我可以采用另一种更简单的方法?
编辑(10/17/12):
我已经更新了下面的jQuery以包含Ryan Wheale代码的一部分,这是当前状态:
- “clickoutside”适用于当前开放范围
- 打开另一个范围会关闭当前范围,然后关闭新范围
jQuery:http://www.eclipsisna.com/?ena=services
$(".service_outline a, .service_title a, .service_price a").click(function() {
$(this).closest("a").children("span").fadeToggle("fast", function() {
$("span").not(this).fadeOut("fast");
});
$(this).one("clickoutside", function () {
$("span").fadeOut("fast");
});
});
HTML:
<td class="service_outline">
<h11><a>Opti-<br><h12>Coat</h12><span><font color="#ffcc00">•</font> Application of permanent, nano ceramic clear resin coating (replaces "Wax"/"Sealant")<br><font color="#ffcc00">•</font> Extended durability for 2+ years<br><font color="#ffcc00">•</font> $250<p><center><img src="images/opti-coat.png"></center></span></a></h11>
</td>
答案 0 :(得分:0)
如果你使用Ben Allman的clickoutside
插件found here,你的生活很简单:
http://jsfiddle.net/ryanwheale/c89Vr/
var $links = $(".service_outline a, .service_title a, .service_price a"),
$dialogs = $links.find( 'span' );
$links.on( 'click', showDialog );
/* -- EDIT: old code kept for historical purposes
$dialogs.on( 'clickoutside', hideDialogs );
*/
function showDialog (ev) {
var $thisDialog = $(this).find( 'span' );
/* -- EDIT: old code kept here for historical purposes
$dialogs.not( $thisDialog ).fadeOut();
*/
if(!$thisDialog.is(':visible')) {
$thisDialog.fadeIn();
/* -- EDIT: New code */
setTimeout( function() {
// IMPORTANT: touch events only supported when you use the
// modified plugin at the bottom of this example
$thisDialog.one('clickoutside.closeDialog, touchstartoutside.closeDialog', function() {
$thisDialog.unbind('.closeDialog').fadeOut();
});
}, 0);
}
}
/* -- EDIT: old code kept here for historical purposes
function hideDialogs() {
$dialogs.fadeOut();
}
*/
/*
* jQuery outside events - v1.1 - 3/16/2010
* http://benalman.com/projects/jquery-outside-events-plugin/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
* IMPORTANT: Modified to support touch events
*/
(function($,c,b){$.map("click dblclick mousemove mousedown mouseup mouseover mouseout change select submit keydown keypress keyup touchstart touchmove touchend".split(" "),function(d){a(d)});a("focusin","focus"+b);a("focusout","blur"+b);$.addOutsideEvent=a;function a(g,e){e=e||g+b;var d=$(),h=g+"."+e+"-special-event";$.event.special[e]={setup:function(){d=d.add(this);if(d.length===1){$(c).bind(h,f)}},teardown:function(){d=d.not(this);if(d.length===0){$(c).unbind(h)}},add:function(i){var j=i.handler;i.handler=function(l,k){l.target=k;j.apply(this,arguments)}}};function f(i){$(d).each(function(){var j=$(this);if(this!==i.target&&!j.has(i.target).length){j.triggerHandler(e,[i.target])}})}}})(jQuery,document,"outside");