当页面加载 Javascript 时激活 :focus

Activate :focus when the page loads with Javascript

我有一个显示 2 个按钮和 1 个 iframe 的页面。这 2 个按钮(按钮 A 和 B)控制 iframe 的内容。我做了一个伪 class (.button:focus) 这样用户就可以看到 iframe 中当前处于活动状态的内容。

页面以 A 开始活动。所以我想要的是,当用户加载页面时,按钮 A 的 .button:focus 处于活动状态。这样一来,哪些内容当前在 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,以便您可以轻松 select 它们(或者至少是您希望关注的 <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,您可以 select 通过 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" >