简体   繁体   中英

What is the difference between window.focus() and window.blur()?

I'm new learner of JavaScript ...I couldn't find out the difference between window.focus(); and window.blur(); .

<!DOCTYPE html>
<html>
<body>
<button onclick="focus()">Click</button>
<script>
 function focus() {
var myWindow = window.open("", "", "width=200,height=100");
myWindow.document.write("<p>A new window!</p>");
myWindow.focus();
}
</script>
</body>


When I am using them I cant find out any action on window by them....

Help me to find out the use of them ...:)

They are basically opposite:

window.focus Assure that the new window GETS focus (send the new window to the front).

window.blur Assure that the new window does NOT get focus (send the new window to the background).

Examples:

- window.focus() :

var myWindow = window.open("", "", "width=200, height=100"); // Opens a new window
myWindow.document.write("<p>A new window!</p>"); // Some text in the new window
myWindow.focus(); // Assures that the new window gets focus

- window.blur() :

var myWindow = window.open("", "", "width=200, height=100"); // Opens a new window
myWindow.document.write("<p>A new window!</p>"); // Some text in the new window
myWindow.blur(); // Assures that the new window does NOT get focus

The window.focus allows to focus on the window. The window.blur() method is the programmatic equivalent of the user shifting focus away from the current window.For more information check the lik below

https://developer.mozilla.org/en-US/docs/Web/API/Window

you can use chrome console to run this code
1. var myWindow = window.open("http://www.runoob.com","newwindow", "width=200,height=100"); 2. myWindow.focus();
3. myWindow.blur();
after run this three line code you can understand what's the difference between window.focus() and window.blur()

I got answer...This code is very useful to know the actions by both of them..

 var focus = true;
 window.onblur = function() { focus = true; document.title="NEW MESSAGE";}
 window.onfocus = function() { focus = true; document.title="Talk"; }
 document.onblur = window.onblur;
 document.focus = window.focus;

 function msg(){
 window.open("https://www.google.co.in/?gfe_rd=cr&ei=luC_V_v_C8aAoAP-7ofwDA")
if(focus) {
    document.title="Talk";
} else {
    document.title="NEW MESSAGE";
}
}
msg();`

I got answer from the following link

refer following link

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