【问题标题】:How to Load a page in a dynamically generated iFrame when a link is clicked like a lightbox in jQuery?当像 jQuery 中的灯箱一样单击链接时,如何在动态生成的 iFrame 中加载页面?
【发布时间】:2011-03-01 14:15:49
【问题描述】:

我有一个链接列表,例如:

<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 做到这一点?

【问题讨论】:

    标签: jquery iframe hyperlink lightbox


    【解决方案1】:
    $(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

    【讨论】:

      【解决方案2】:

      你可以这样做:

      // 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' 添加到&lt;ul&gt; 可能是最好的选择.您还可以使用 css 属性/类来设置 &lt;iframe&gt; 的样式。

      Demo on jsfiddle

      【讨论】:

      • 嘿,谢谢,jsfiddle 真的很好。感谢您的代码和 jsfiddle 介绍
      • @Aakash Chakravarthy - 没问题 - 此外,您可以通过点击帖子分数下方的复选框将答案标记为“已接受”。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多