简体   繁体   中英

window.blur() - what am I doing wrong

I'm trying to unfocus a window when it's opened, the situation is:

  • I have a main window with a button which open a new window when it's clicked and automatically call the blur() method so the window should be in background, but nothing is happening, I tried it on last versions of Firefox and Chrome.

     function openWindow() { var exampleWin = window.open('example.html','Example','width=500,height=500'); exampleWin.blur(); } // and the HTML: <button onclick="openWindow();">Open Window</button> 

The code is so simple, but I'm not sure why it doesn't work, I even look at the MDN documentation and all seems ok.

-- Edit --

Finally I've found a solution with a little different approach:

function openWindow() {
            /* This time I don't use var keyword, so the exampleWin variable 
               will have a global scope */
    exampleWin = window.open('example.html','Example','width=500,height=500');
}

function focusFn() {
    exampleWin.focus();
}

function blurFn() {
    exampleWin.blur();
}

// The HTML:
<button onclick="openWindow();">Open Window</button>
<button onclick="focusFn();">Focus</button>
<button onclick="blurFn();">Blur</button>

It works properly this way, but just if I call the focus/blur functions with the onclick event, not if I call them inside the openWindow() function, anyway it's fine for me.

Try giving the main window focus instead:

function openWindow() {
  var exampleWin = window.open('example.html','Example','width=500,height=500');
  window.focus();
}

使用exampleWin.focus()而不是exampleWin.blur()

Do this it works better for most conditions...

$('a').click(function(e){
    e.preventDefault();
    var evt = document.createEvent("MouseEvents"),
        ele = document.createElement('a');

    ele.href = $(this)[0].href;
    evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, false, 0, null);
    ele.dispatchEvent(evt);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM