Down below is a fully working example of the lightbox (aka thickbox) effect described in the previous article. Note that the technique has even been improved, since the script now prevents by itself a link from being opened. As a result, you do not need to place the target URL as a custom attribute anymore. Just append a class to an anchor and the script is ready to be used!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script>
jQuery(document).ready(function(){
$('.isLink').click(function(ev){
// this below prevents the link from being followed
ev.preventDefault();
ev.stopPropagation();
if($("#mylightbox").length==0){
var sH=$(document).height(), sW=$(document).width(), scPos=$(document).scrollTop();
var tgtURL=$(this).attr("href");
$("body").css("overflow","hidden");
$("body").append("<div id=mylightbox style='position:absolute; z-index:1000; top:0px; left:0px; opacity:0.75; filter:opacity(alpha=0,75); width:"+(sW+20)+"px; height:"+sH+"px; background:#aaa;'></div>");
$("body").append("<div id=full-image-bg style='z-index:1001; width:100%; height:100%; position:absolute; left:0px; top:"+scPos+"px;'><img id=full-image-img src='"+tgtURL+"' style='position:absolute; width:auto; height:auto; cursor:pointer;'/></div>");
var picW=$("#full-image-img").width(), picH=$("#full-image-img").height(), lbW=$("#full-image-bg").width(), lbH=$("#full-image-bg").height();
var cX=(lbW/2)-(picW/2), cY=(lbH/2)-(picH/2);
$("#full-image-img").css("left",cX+"px").css("top",cY+"px");
$("#full-image-img").click(function(){
$("#full-image-bg").remove();
$("#mylightbox").remove();
if($("body").height() > $(window).height()){
$("body").css("overflow","scroll");
$("body").css("overflow-x","hidden");}
});
}
});
});
</script>
</head>
<body>
<a href="https://www.google.com/images/srpr/logo4w.png" class="isLink">Click me!</a>
<!-- class="isLink" is the only thing needed to tell the browser you want to display the target image in a lightbox -->
</body>
</html>
Commentaires
Enregistrer un commentaire