如何在jQuery中像在Lightbox中一样点击链接时在动态生成的iFrame中加载页面?
问题描述:
我有联系例如列表:如何在jQuery中像在Lightbox中一样点击链接时在动态生成的iFrame中加载页面?
<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>
当点击一个链接时,应在屏幕加载页面类似灯箱的中间产生的iFrame。
如何用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();
});
});
我不好计算顶部/左坐标那里,你可能要替换成一个CSS类反正。创建时使用class: "classname"
。
参考文献:.bind(),。 attr(),.appendTo(),jQuery Core
答
你可以做这样的事情:
// 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;
});
当然比一个演示其他任何东西,你会希望有一个更具体的选择比a
这将找到的每一个环节,像.myLinks a
并添加class='mylinks'
到<ul>
可能是最好的选择。您还可以使用更多选项来使用css属性/类来设置的样式。
嘿谢谢你,jsfiddle真的很好。谢谢你的代码和介绍jsfiddle – 2010-06-09 12:47:02
@Aakash Chakravarthy - 没问题 - 同样,你可以通过点击帖子评分下面的复选框来标记答案为“接受”。 – gnarf 2010-06-09 12:48:26