简体   繁体   中英

Activate :focus when the page loads with Javascript

I have a page which displays 2 buttons and 1 iframe. These 2 buttons (button A and B) control the content of the iframe. I have made a pseudo class (.button:focus) so the user can see which content is currently active in the iframe.

The page starts with A active. So what I want is that .button:focus is active for button A when the user loads the page. That way it is clear which content is currently active in the iframe. I have looked in to using an onload function on the body, but couldn't set up the proper function.

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;

Give your elements an ID so that you can select them easily (or at least the <a> you wish to focus).

 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> 

Or, if you are unable to edit the html for whatever reason you could select by href attribute:

 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> 

You could do this without Javascript but you would have to change your <a> s to <input type="button"> . This would allow you to use the autofocus property:

 <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" > 

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