iframe定义为null

时间:2018-11-22 17:39:33

标签: javascript jquery html iframe

我的iframe应该在点击红色按钮后关闭,有时应该更改其src,但Chrome认为我的iframe为空。这是我的网站:https://broenot.netlify.com/articles/20-11-18 这是我的banners.js代码:

var bannerid = Math.floor(Math.random() * 2);
var bannerclosed = localStorage.getItem("bannerclosed");
  if (bannerclosed == "yes"){
    document.getElementById("ibanner").style.visibility = "hidden";
  }
  if (bannerid == 1){
    document.getElementById("ibanner").src = "/banners/banner2.html";
  }
  $('#banner').load(function(){
    var iframe = $('#ibanner').contents();
    iframe.find("#close").click(function(){
      $("#ibanner" ).animate({opacity: 0}, 500)
      setTimeout(bannerclose, 500); 
    });
  });
  function bannerclose(){
    document.getElementById("ibanner").style.visibility = "hidden";
    localStorage.setItem("bannerclosed", "yes");
  }

HTML:

<iframe src="/banners/banner1.html" frameborder="0" style="width: 40%; height: 150px; position: fixed; bottom: 0; left: 0; border-radius: 15px;" id="ibanner"></iframe>

如果需要,可以使用F12在网站上获取其他内容。

1 个答案:

答案 0 :(得分:0)

如果仅设置localStorage项,则网址不会更改。首先,您必须在storage事件上添加事件监听器:

编辑:为避免歧义,请使用.ready()而不是.load()

window.addEventListener('storage', function(event){
    if (event.storageArea === localStorage) {
        var bannerclosed = localStorage.getItem("bannerclosed");
        if (bannerclosed == "yes"){
            document.getElementById("ibanner").style.visibility = "hidden";
        }
        if (bannerid == 1){
            document.getElementById("ibanner").src = "/banners/banner2.html";
        }
    }
}, false);

$('#ibanner').ready(function(){
  var $iframe = $('#ibanner');
  $iframe.find("#close").click(function(){
    $iframe.animate({opacity: 0}, 500);
    setTimeout(bannerclose, 500); 
  });
});

function bannerclose(){
    document.getElementById("ibanner").style.visibility = "hidden";
    localStorage.setItem("bannerclosed", "yes");
}