在第二次加载时更改 iframe 样式,在 Internet Explorer 9 中不起作用

Change iframe style on second load, doesn't work in Internet Explorer 9

本文关键字:Internet Explorer 不起作用 iframe 加载 第二次 样式      更新时间:2023-09-26

我正在尝试在第二次加载时更改 iframe 的样式。我试过这个:

$(function() {
    var loadCnt = 0;
    $('#iframem').load(function() {
        if (loadCnt >0) {
            $("#idiv").width(453).height(349);
            $("#iframem").css("left", "-656px");
            $("#iframem").css("top", "-250px");
        }
        ++loadCnt;
    });
});

.HTML:

<div style="overflow: hidden; width: 377px; height: 230px; position: relative;" id="idiv">
<iframe  id="iframem" src="http://www.example.org" style="border: 0pt none ; left: -1px; top: -8px; position: absolute; width: 1680px; height: 867px;" scrolling="no"></iframe></div>

它运行良好,但它不适用于Internet Explorer 9。正确的方法是什么?

我认为您的方法存在逻辑问题,并且不确定您如何使其工作。由于 JavaScript 仅在页面加载后运行,这意味着在您的代码中,您实际上永远不会loadCnt大于 1 - 因为每次加载页面时,它都会再次将其设置为 0。

为了实现你所描述的,你需要采取不同的方法,有几种方法可以做到这一点:

  1. 使用服务器端语言并使用会话变量,其中设置了负载计数

  2. 如果您的页面通过 Ajax 加载并注入到 DOM,那么,例如,如果您的代码位于主页上的第一个"真实"加载页面loadCnt,然后在页面之间移动时您再次"加载"主页,实际上您没有加载整个JavaScript脚本,只需将HTML重新注入文档,然后您可以添加使用该loadCnt的侦听器。

  3. 使用 JavaScript localStorage - 在第一次加载时,您将设置在本地存储对象上与 0 相反,您将能够在以后加载时检索:

    if (localStorage.getItem("counter") === null) {
        // Check if the item exists; if not set it to 0 as it is the first run
        localStorage.setItem('counter', 0);
    }
    else {
        // Get the counter - here you can do your work for when the page is loaded after the first load
        localStorage.getItem('counter');
    }
    
  4. 使用 Javascript cookie 执行与前面逻辑相同的操作,但在 cookie 中(因为 localStorage 可能存在兼容性问题)

应始终使用 onload 属性来设置任何函数。在 Internet Explorer 中,不能通过代码设置 onload 事件。有办法做到这一点,我在答案的选项 2 中提到过。

选项 1

.HTML

<div style="overflow: hidden; width: 377px; height: 230px; position: relative;" id="idiv">
    <iframe  id="iframem" src="http://www.example.com" style="border: 0pt none ; left: -1px; top: -8px; position: absolute; width: 1680px; height: 867px;" scrolling="no" onload="myIframeLoadFunction()">
    </iframe>
</div>

JavaScript 代码

var loadCnt = 0;
function myIframeLoadFunction(){
    if (loadCnt >0) {
        $("#idiv").width(453).height(349);
        $("#iframem").css("left", "-656px");
        $("#iframem").css("top", "-250px");
    }
    ++loadCnt;
}

选项 2

您需要在元素在 HTML 上呈现后专门绑定 onload 事件。

JavaScript 代码

(function (selector) {
    var loadCnt = 0, frame = $(selector).get(0);
    if (frame) {
        frame.onload = function () {
            if (loadCnt >0) {
              $("#idiv").width(453).height(349);
              $("#iframem").css("left", "-656px");
              $("#iframem").css("top", "-250px");
            }
            ++loadCnt;
        };
    }
})('#iframem');