![](/img/trans.png)
[英]How can I focus() to another window on javascript, when the page loads?
[英]Activate :focus when the page loads with Javascript
我有一个页面,其中显示2个按钮和1个iframe。 这两个按钮(按钮A和B)控制iframe的内容。 我做了一个伪类(.button:focus),以便用户可以看到iframe中当前处于活动状态的内容。
该页面以A active开头。 所以我想要的是当用户加载页面时.button:focus对于按钮A处于活动状态。 这样一来,就可以清楚地了解iframe中当前处于活动状态的内容。 我已经考虑过在身体上使用onload函数,但是无法设置适当的函数。
HTML:
<body>
<div id="load">
<a class="button" href="Test_Hoover_A.html" target="Targetframe">Schets A</a>
</div>
<a class="button" href="Test_Hoover_B.html" target="Targetframe">Schets B</a>
<br>
<br>
<br>
<iframe src="Test_Hoover_A.html" name = "Targetframe" height=700 width=900 style="border:2px solid green;" ></iframe>
</body>
CSS:
.button {
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
float: left;
-webkit-transition-duration: 0.4s;
}
.button:focus {
background-color: #3e8e41;
}
.button:hover {
background-color: #555555;
color: white;
给您的元素一个ID,以便您可以轻松地选择它们(或至少选择要聚焦的<a>
)。
document.getElementById('btnA').focus();
.button { background-color: #4CAF50; /* Green */ border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; cursor: pointer; float: left; -webkit-transition-duration: 0.4s; } .button:focus { background-color: #3e8e41; } .button:hover { background-color: #555555; color: white; }
<a id="btnA" class="button" href="Test_Hoover_A.html" target="Targetframe">Schets A</a> <a id="btnB" class="button" href="Test_Hoover_B.html" target="Targetframe">Schets B</a>
或者,如果由于任何原因而无法编辑html,则可以通过href属性进行选择:
document.querySelectorAll("a[href='Test_Hoover_A.html']")[0].focus();
<a id="btnA" class="button" href="Test_Hoover_A.html" target="Targetframe">Schets A</a> <a id="btnB" class="button" href="Test_Hoover_B.html" target="Targetframe">Schets B</a>
您可以在没有Javascript的情况下执行此操作,但必须将<a>
更改为<input type="button">
。 这将允许您使用autofocus
属性:
<input type="button" class="button" href="Test_Hoover_A.html" target="Targetframe" value="Schets A" autofocus> <input type="button" class="button" href="Test_Hoover_B.html" target="Targetframe" value="Schets B" >
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.