【问题标题】:jQuery - Change Iframe height in the onclick event of a button inside the iframejQuery - 在 iframe 内的按钮的 onclick 事件中更改 iframe 高度
【发布时间】:2014-11-01 04:48:11
【问题描述】:

现在我正在编写一个简单的 HTML/jQuery 脚本,当我点击一个由 iframe 自行加载的按钮时,我想更改 iframe 的高度。

看看我的代码:

index.php:

<div id="outerdiv">
    <iframe src="http://beta.sportsdirect.bg/test/iframe.php" id="inneriframe" scrolling="no"    target="_parent"></iframe>
</div>

iframe.php:

 <HTML>
 <head>
 <script src="//code.jquery.com/jquery-1.10.2.js"></script>
 </head>
    <script type="text/javascript">
    $("#SuperWebF1").click(function(){

        $('#inneriframe, #outerdiv', window.parent.document).css({"height":"450px"});

    })
    </script>
 <div style="display:block;height:300px;">
    <h3>The iframe content</h3>  
        <button type="button" id="SuperWebF1">Click me to resize the holding Iframe!</button>
  </div>        

这里是 index.php 的演示:http://beta.sportsdirect.bg/test/

当您打开它时,您会看到 iframe 加载的按钮。 当您单击按钮时,iframe 不会改变高度!

为什么,有错误吗?

你能帮我做这件事吗?

提前致谢!

【问题讨论】:

  • 您正试图在按钮元素存在之前将点击事件绑定到它。
  • 有什么方法可以将脚本放在 iframe 之外并让它在按钮上点击 iframe 内的按钮?

标签: javascript jquery html button iframe


【解决方案1】:

以下是我对您的代码所做的一些更改。

//function call needed to make sure page is loaded before javascript runs
$(document).ready(function(){//begin document ready function

//on click event
$(document).on("click","#SuperWebF1",function(){//begin on click event

    //change the height of selected elements
    $('#inneriframe, #outerdiv', window.parent.document).css({"height":"450px"});

    });//end on click event


  });//end document ready function

【讨论】:

  • 有什么方法可以将脚本放在 iframe 之外并让它监听在按钮上的 iframe 内点击
【解决方案2】:

您需要先获取 iframe 的内容,然后才能设置点击事件。试试这个 -

var iframeDoc = $('#inneriframe').contents().get(0);
$(iframeDoc).on('click', 'SuperWebF1', function() {
       ........... your code here  .............
});

编码愉快!!!

【讨论】:

    猜你喜欢
    • 2014-12-28
    • 2014-12-25
    • 1970-01-01
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-21
    相关资源
    最近更新 更多