Skip to main content
 首页 » 编程设计

c#之JavaScript 的 window.focus() 不适用于 IE9

2024年02月23日54mayingbao

这是我的代码

protected void LoginButton_Click(object sender, EventArgs e) 
    { 
        if (DAL.DAOKullanici.Login(KullaniciTextBox.Text,SifreTextBox.Text)) 
        { 
            VeriyazPROTicari.Sessionlar.Variables.loginkontrol = true; 
 
            Session["kullaniciAdi"] = KullaniciTextBox.Text; 
            Session["kullaniciId"] = DAL.DAOKullanici.GetEntity(DAL.DAOKullanici.KullaniciAdiIleKullaniciIdCek(KullaniciTextBox.Text)).ID; 
 
            bool main_window_open = false; 
 
            if (!main_window_open) 
            { 
                Page.RegisterClientScriptBlock("Main_Window", "<script>" + 
                "var newwindow; " + 
                "newwindow = window.open('" + "/dashboard/dashboard.aspx" + "', 'main_app_window', ' toolbar=0,location=0,directories=0,status=1,menubar=0,left=1,top=1,scrollbars=" + "1" + ",resizable=1,width=" + "1280" + ",height=" + "800" + "'); " + 
                "if (window.focus) " + 
                "{newwindow.focus();} " 
                + "</script>"); 
 
                main_window_open = true; 
 
 
            } 
            HataLabel.Text = ""; 
        } 
        else 
        { 
            HataLabel.Text="Hatalı Giriş"; 
        } 
    } 

除了 JavaScript 部分,我没有任何问题。

我想做的是在单击 LoginButton 后打开 dashboard.aspx 并设置焦点。此代码打开 dashboard.aspx 并在 Google Chrome 和 Mozilla Firefox 4 中设置焦点。但是,当我在 IE9 上尝试时,dashboard.aspx 已打开,但焦点不起作用并且 dashboard.aspx 保留在登录页面下。

如何在 IE9 上将焦点设置在新窗口上?

请您参考如下方法:

我遇到过与此类似的问题,它似乎发生了,因为在 IE9(和任何 IE)中,focus() 方法在窗口呈现之前运行。

为了解决这个问题,我认为有两种方法可以解决这个问题:

  1. 设置一个计时器,在一小段时间后加载焦点。
  2. 推迟 JavaScript 的读取,直到窗口完全呈现。

计时器方法对我来说不是我的首选,因为在我个人看来它很困惑,如果页面加载时间比计时器更长,你就会遇到同样的问题。要实现计时器,您可以使用类似的东西:

Page.RegisterClientScriptBlock("Main_Window", "<script>" + 
    "setTimeout(function() { " + 
    "var newwindow; " + 
    "newwindow = window.open('" + "/dashboard/dashboard.aspx" + "', 'main_app_window', ' toolbar=0,location=0,directories=0,status=1,menubar=0,left=1,top=1,scrollbars=" + "1" + ",resizable=1,width=" + "1280" + ",height=" + "800" + "'); " + 
    "if (window.focus) " + 
    "{newwindow.focus();} " + 
    "}, 5);" + 
    "</script>"); 

我设置了 5 秒的延迟,这可能有点矫枉过正。

defer 方法是我的首选,因为我觉得它更干净、更简单,但它可能有效也可能无效:

Page.RegisterClientScriptBlock("Main_Window", "<script type="text/javascript" defer="defer">" + 
    "var newwindow; " + 
    "newwindow = window.open('" + "/dashboard/dashboard.aspx" + "', 'main_app_window', ' toolbar=0,location=0,directories=0,status=1,menubar=0,left=1,top=1,scrollbars=" + "1" + ",resizable=1,width=" + "1280" + ",height=" + "800" + "'); " + 
    "if (window.focus) " + 
    "{newwindow.focus();} " 
    + "</script>");