How to make the left div scrollable with space bar

2019-08-26 07:03发布

问题:

This question already has an answer here:

  • Autofocus to a div so we can use arrow keys to scroll without having to click first 4 answers

When you navigate on a page like this one, you can immediately use SPACE BAR or UP/DOWN ARROW or PG UP/DOWN to scroll the page, without having to click on the background of the page first.

How to make that the following page also scrolls with these keys, without requiring a click on #left div first? (see "live demo" link at the end of question)

<div id="main">
    <div id="header">
        <div id="topleft">LOGO</div>
        <div id="topright">TOPRIGHT</div>
        <div id="topmid">TOPMID</div>
    </div>

    <div id="mapcontainer"><div id="map"></div></div>

    <div id="left">
        <div id="leftmain">
            <div id="list">AAa<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>b<br>c<br>c<br>c<br>c<br>c<br>c<br>c<br>c<br>c<br>c<br>c<br>c<br>c<br>c<br>c<br>c<br>c<br>c<br></div>
        </div>
    </div>
</div>

Here is the CSS:

* { margin: 0; padding: 0; }
body { overflow: hidden; height: 100%; }
#left { height:calc(100% - 60px); width: 54%; float: left; padding: 0 2%; overflow-y: auto; }
#mapcontainer { height:100%; position: absolute; left: 58%; width: 42%; }
#map { height: 100%; }
#topleft { float: left; width: 155px; }
#topright { float: right; width: 50%; }
#header { height: 60px; background-color: #eee; }

I tried:

  • with tabindex="0" on #left div but it doesn't work
  • by triggering a click on #left div via JavaScript / jQuery with $("#left").click() but it doesn't work either.

Here is a live demo.

Note: I didn't embed a SO code snippet (I tried) because when you click Run, it doesn't give focus to the page, so you have to click on the page anyway, so you cannot observe what I mean. It would be same problem with a jsfiddle.

回答1:

Not sure if I got you right. Here's a Codepen with fixed header and fixed map. This is achieved by using position: fixed on the header and map.