jquery------使用jQuery的委托方法
index.jsp
<div id="gallery"> <div class="photo"> <img src="addimage/p1.jpg"> <div class="details"> <div class="author">Me</div> <div class="date">2016/5/22</div> </div> </div> <div class="photo"> <img src="addimage/p2.jpg"> <div class="details"> <div class="author">Me</div> <div class="date">2016/5/23</div> </div> </div> <div class="photo"> <img src="addimage/p3.jpg"> <div class="details"> <div class="author">Me</div> <div class="date">2016/5/24</div> </div> </div> </div>
my.js
$(document).ready(function(){ /*$("div.photo").each(function(index){ $(this).hover(function(){ var $left=$(this).offset().left+120; var $top=$(this).offset().top-150; $(this).find(".details").fadeTo(1000,1.0).css({left:$left,top:$top,}); $(this).fadeTo(1000,0.5); },function(){ $(this).find(".details").fadeTo(1000,0); $(this).fadeTo(200,1.0); }); });*/ /*$("div.photo").on("mouseenter mouseleave",function(event){ var $details=$(this).find(".details"); var $left=$(this).offset().left+120; var $top=$(this).offset().top-150; if(event.type=="mouseenter"){ $details.toggleClass("showtime",event.type=="mouseenter"); $details.fadeTo(1000,1.0).css({left:$left,top:$top,}); $(this).fadeTo(1000,0.5); } else{ $details.fadeOut("fast"); $(this).fadeTo(200,1.0); } });*/ //jquery中的事件委托 $("#gallery").on("mouseenter mouseleave","div.photo",function(event){ var $details=$(this).find(".details");//this是div.photo var $top=$("div.photo").offset().top-30; var $left=$details.closest("div.photo").offset().left+220; if(event.type=="mouseenter"){ $details.fadeTo("fast",1.0).css({top:$top,left:$left}); $details.closest("div.photo").find("img").css({opacity:0.5}); } else{ $details.fadeOut("fast"); $details.closest("div.photo").find("img").css({opacity:1.0}); } }); });
css.css
.photo{ display:inline; } img{ width:300px; height:200px; } .details{ position:absolute; display:none; color:#fff; } .showtime{ border:2px solid #aaa; }