window.focus()和window.blur()有什么区别?

时间:2016-08-26 04:45:44

标签: javascript

我是JavaScript的新学习者......我无法找出window.focus();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>

当我使用它们时,我无法通过它们找到窗口上的任何动作....

帮我看看它们的使用...... :)

4 个答案:

答案 0 :(得分:4)

他们基本相反:

window.focus确保新窗口 GETS 聚焦(将新窗口发送到前面)。

window.blur确保新窗口 NOT 获得焦点(将新窗口发送到后台)。

示例:

- 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

答案 1 :(得分:2)

window.focus允许对焦于窗口。 window.blur()方法是用户将焦点从当前窗口移开的程序化等效物。有关更多信息,请查看以下内容

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

答案 2 :(得分:2)

您可以使用chrome控制台来运行此代码 1。var myWindow = window.open("http://www.runoob.com","newwindow", "width=200,height=100"); 2。myWindow.focus();
3。myWindow.blur();
运行这三行代码后,你可以理解window.focus()和window.blur()之间的区别是什么

答案 3 :(得分:0)

我得到了答案......这段代码对于了解两者的行为非常有用..

 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();`

我从以下链接获得了答案

  

refer following link