开发者

How to Load a page in a dynamically generated iFrame when a link is clicked like a lightbox in jQuery?

I have a list开发者_开发技巧 of links eg :

<ul> 
<li><a href="http://google.com">Link1</a></li>
<li><a href="http://example.com">Link2</a></li>
<li><a href="http://example.com/sdf">Link3</a></li>
</ul>

When a link is clicked, a iFrame should be generated in the middle of the screen loading the page like a lightbox.

How to do this with jQuery ?


$(document).ready(function(){
 $('a').bind('click', function(e){
    $('<iframe/>', {
       src:   $(this).attr('href'),
       class: 'myiframe',
       css:   {
           position: 'absolute',
           width:    '200px',
           height:   '200px',
           top:      window.innerHeight / 2 + 300,
           left:     window.innerWidth / 2 + 300
       }          
    }).appendTo(document.body);

    return(false);
});

$(document.body).bind('keydown', function(e){
  if(e.which === 27)
     $('.myiframe').remove();
});
});​

I poorly calculated the top/left coordinates there, you might want to replace that with a css class anyway. Use class: "classname" for that within creation.

References: .bind(), .attr(), .appendTo(), jQuery Core


You can do something like this:

// we only want to use a single iframe:
var $iframe = $("<iframe>").css({
  width: '100%', 
  height: '10em'
  // we can set more css properties to make it positioned where we want, etc...
});
$("a").click(function() {
   // stick it at the end of the <body> tag, and set its src property
   $iframe.appendTo('body').attr('src',this.href);
   return false;
});

Of course for anything other than a demo, you'll want a more specific selector than a which will find every link, something like .myLinks a and add class='mylinks' to the <ul> is probably the best option. You also have more options for styling the <iframe> using css properties/classes.

Demo on jsfiddle

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜