问题
In the following example, I use checkbox for making a pure CSS dropdown navigation, also available in this jsFiddle example.
Open that fiddle, click "Menu", click "Link 1", and click the "Back" button on the browser toolbar, as you can see the checkbox remains checked, so the navigation is still open.
My question is - would it be possible to reset that checkbox to unchecked automatically when going back from the browser history? Any suggestions please? Do I need to use Javascript/jQuery?
HTML
<label for="m">Menu</label>
<input id="m" type="checkbox">
<nav id="n">
<ul>
<li><a href="//example.com">Link 1</a></li>
</ul>
</nav>
CSS
#n {
display: none;
}
#m:checked ~ #n {
display: block;
}
回答1:
No need for JS or CSS, just add autocomplete="off"
to the checkbox. This will prevent the browser from caching the 'checked' status.
Example: https://jsfiddle.net/6g5u8wkb/
Also, if you have multiple checkboxes, I beleive you can add autocomplete="off"
to the form
element to apply the effect to all inputs fields.
回答2:
Try adding something like this:
$( document ).ready(function() {
$("#m").prop('checked',false );
});
$( document ).ready(function() {
$("#m").prop('checked',false );
});
#n {
display: none;
}
#m:checked ~ #n {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="m">Menu</label>
<input id="m" type="checkbox">
<nav id="n">
<ul>
<li><a href="//example.com">Link 1</a></li>
</ul>
</nav>
回答3:
Further to the other comments, if you are writing an AJAX driven page that uses pushState/replaceState, and the back button would not actually reload a page (i.e. no HTTP request), you can listen for the popState
event and clear the checkbox.
window.onpopstate = function(event) {
$("#m").prop('checked',false );
};
It's a HTML 5 feature that's not fully supported across all browsers (although support is pretty good)
https://developer.mozilla.org/en-US/docs/Web/Events/popstate
Other options would be to use libraries like history.js, jquery-bbq, sammyjs, and so on.
回答4:
add autocomplete="off"
to the checkbox.
来源:https://stackoverflow.com/questions/37933043/reset-checkbox-checked-state-go-back-from-history