【问题标题】:Load iframe when user clicks on modal当用户点击模态框时加载 iframe
【发布时间】:2016-03-14 14:22:00
【问题描述】:

我的网站中有一个页面,其中包含大约 60 个 iframe 元素。这些 iframe 包含在 w3-modals div 中,但在页面加载后都会立即加载,导致页面加载非常缓慢。当用户单击按钮加载 w3-modal 时,是否有可能加载 iframe 以帮助页面加载时间。

对此的任何帮助将不胜感激!但如果可能的话,请保持简单,因为我是编码新手。

非常感谢!

这是我使用的代码:

加载模式的按钮

<button onclick="document.getElementById('id03').style.display='block'" class="w3-btn w3-light-blue">Instruction</button>

模式代码

<div id="id03" class="w3-modal">
      <iframe src="http://" frameborder="0" height="700px" style="width: 800px">

【问题讨论】:

  • 我认为this 会帮助你。这个问题看起来一样。

标签: javascript jquery html


【解决方案1】:

我认为您采取了错误的方式。加载 60 个不同的页面太疯狂了,而且您的计算机和浏览器肯定会遇到这种情况。

我认为更好的方法是(如您所说)根据请求加载 iframe。我假设你所有的 iframe 都是隐藏的(和you are using this modal system),所以我们可以这样做:

<button class="w3-btn w3-light-blue" data-open-modal="id03">Instruction</button>
<div id="id03" class="w3-modal" data-url="your-iframe-url"></div>

您首先使用数据属性data-open-modal 定义了button,这表明此按钮将打开一个模式。接下来,您的模态divdata-url 定义了要在iframe 中使用的URL。所以,这是用 JavaScript 来解决问题的(使用 jQuery,抱歉没有时间使用 vanilla):

// We find all the buttons 'data-open-modal'
$('[data-open-modal]').click(function (e) {
    // We get the ID of the modal to open
    var modalId = $(this).data('open-modal');
    // We set a modal reference (shortcut)
    var $modal = $(modalId);
    // We get the iframe URL from the modal data-url
    var iframeURL = $modal.data('url');
    // We show the modal
    $modal.display(); // display: block;
    // We create the iframe inside using the URL
    $modal.append('<iframe src="' + iframeURL + '" frameborder="0" height="700px" style="width: 800px">');
    // We bind a click event when the user clicks on the "X" to close the modal and whe delete the iframe
    $modal.find('.w3-closebtn').on('click', function (e) {
        $modal.find('iframe').remove(); // Delete the iframe
    });
});

我还没有测试过这段代码,但它应该可以工作!

【讨论】:

    【解决方案2】:
    var your_source = $('#source').val();
    $("#button").click(function () { 
          $("iframe").attr("src", your_source);
    });
    

    【讨论】:

    • 请描述这是在做什么以及为什么选择以这种方式这样做,以便帮助教育您的读者。
    猜你喜欢
    • 1970-01-01
    • 2015-06-20
    • 2012-05-22
    • 2018-09-10
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多