简体   繁体   中英

Jump to specific location on the page based on elements class

I have two HTML elements and both of them are hidden at the start:

    <div class="alert alert-danger divMessage" id="lblErrorMobile" style="display:none;"></div>
    <div class="alert alert-success divMessage" id="lblSuccessMobile" style="display:none;"></div>

I know I can navigate to one or the another like this:

window.location.href = '#lblErrorMobile';
window.location.href = '#lblSuccessMobile';

Is it possible to navigate on each of these by class - let's say, a class divMessage ?

My problem is that those labels are not shown by default. They are showing separately if there is error or success. And if I try to navigate on a label which is hidden, navigation does not happen. That is why navigating by class would be so handy - one or the other will be always visible.

It looks like you should use a container for both div that you will jump to instead of having to know which div you should jump to. For instance :

<div id="messages">
    <div class="alert alert-danger divMessage" id="lblErrorMobile" style="display:none;"></div>
    <div class="alert alert-success divMessage" id="lblSuccessMobile" style="display:none;"></div>
</div>

Then jump to #messages .

You can use anchor tags to navigate around your site, without using Javascript.

https://codepen.io/anon/pen/ejrEzL

<h2 id="top">top</h2>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<h2 id="middle">middle</h2>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<h2 id="end">end</h2>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<div style="position: fixed; right: 10px; top: 10px;">
  <a href="#top">go to top</a>
  <a href="#middle">go to middle</a>
  <a href="#end">go to end</a>
</div>

Or using javascript you can using the following method:

var el = document.getElementById("my-element");
el.scrollIntoView();

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