简体   繁体   中英

Be able to scroll within underlying element while cursor is over position absolute element in front of it

How can I be able to scroll article while having my mouse cursor over .header while still having .header clickable? If I set z-index: -1 to .header I'm able to scroll while having the cursor over .header , but it's no longer clickable.

Demo
Fiddle

HTML:

<div class="row">
  <div class="off-canvas-wrap">
      <div class="inner-wrap">
          <div class="header">
              I should be clickable
          </div>

          <article class="small-12 columns">
              <div style="height:5000px">
              </div>
          </article>

      </div>
  </div>
</div>

CSS:

article {
    overflow-y: auto;
}
article,
body,
html,
.off-canvas-wrap, 
.off-canvas-wrap .inner-wrap,
.row {
    height: 100%;
    width: 100%;
}
.header {
    position: absolute;
    width: 400px;
    height: 400px;
    background: #000;
    left: 50%;
    top: 50%;
    margin-left: -200px;
    margin-top: -200px;
    z-index: 1;
    color: #fff;
    text-align: center;
    padding-top: 1em;
}

If you want a CSS solution, there is none — this is because of how mouse events are directly related to the visibility of the item to the pointer/cursor: eg if you place .header in the back such that it is not accessible (so that scroll events on article can be triggered), it will not register a click event, too.

A JS-based solution would be listening to the mousewheel() event (with this plugin , available as a CDN-hosted plugin , too) and then manually triggering scrolling on the article element. However, this does not replicate the default scrolling behavior on individual OSes, and may appear choppy on OSes that has smoothed scrolling events (like OS X).

Without further ado:

// Cache article's position from top (might change if the page is loaded with a hash, so we cannot declare it as 0)
var fromTop = $('article').scrollTop();

$('.header').mousewheel(function(e,d) {
    // Prevent default scrolling behavior, even when .header is overflowing
    e.preventDefault();

    // Trigger scroll in window
    // You can change how much to amplify the 'd', which is the delta (distance registered from the scrollwheel). I have chosen it to multiply it by 10
    fromTop = fromTop - d*10;
    $(this).next('article').scrollTop(fromTop);
}).click(function() {
    // Just testing
    alert('Header is clicked on!');
});

Here is the proof-of-concept JSFiddle: http://jsfiddle.net/teddyrised/CK7z8/2/

Warning: In the event that there are multiple .header elements targeting multiple article elements on the same page, you will have to iterate through each .header - article pair and cache the fromTop separately for each pair.

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