简体   繁体   中英

How do I change my navbar's height based on whether a link is in focus?

I'm using React and javascript to style my webpage, and I have implemented a skip link in my navbar that takes the user further down the page when clicked. This skip link only comes into focus when the user hits the tab key, but it is positioned above the site logo in the navbar and so needs more space when it is visible. I want to increase the height of my navbar when the link is visible, and right now I am using a boolean called linkHasFocus (for some conditional CSS styling), along with a function called checkFocus, to do that:

const TopNavbar = styled. div`
      ...
      height: ${props => (props.linkHasFocus ? '9rem' : '4rem')}; 
      ... 
`;

And here's the checkFocus function:

const checkFocus = () => {
      const elem = document.getElementById('skip-link');
      if (elem === document.activeElement) {
        this.linkHasFocus = true;
      }
      this.linkHasFocus = false;
      return this.linkHasFocus;    
};

I then pass this to my TopNavbar component (which is the parent of my skip link component) in my return function like so:

<TopNavbar linkHasFocus={checkFocus}>

But it seems the checkFocus function isn't updating the linkHasFocus variable correctly. My understanding of props and javascript in general is a little shaky, so apologies if there's glaring issues here.

To focus an elemento you have to use the method .focus() .

Then you could use CSS :focus Selector to change the style (and so the height of the component), when the element is focused.

Example with a <button> element:

 /* Normal */ #skip-link { height: 4rem; } #skip-link:focus { height: 9rem; } /* Smooth transition */ #skip-link-transition { height: 4rem; -webkit-transition: all.5s ease; -moz-transition: all.5s ease; -ms-transition: all.5s linear; -o-transition: all.5s linear; transition: all.5s ease; } #skip-link-transition:focus { height: 9rem; -webkit-transition: all.5s ease; -moz-transition: all.5s ease; -ms-transition: all.5s linear; -o-transition: all.5s linear; transition: all.5s linear; } /* Table CSS */ table, th, td { border: 1px solid; }
 <table> <tr align="center"> <td width="100rem"><b>Normal</b></td> <td width="100rem"><b>Smooth Transition</b></td> </tr> <tr align="center"> <td><button id="skip-link">Test1</button></td> <td><button id="skip-link-transition">Test2</button></td> </tr> </table>

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