【问题标题】:Be able to scroll within underlying element while cursor is over position absolute element in front of it当光标位于其前面的绝对元素上时,能够在底层元素内滚动
【发布时间】:2014-05-17 23:54:20
【问题描述】:

如何在将鼠标光标悬停在.header 上的同时滚动article,同时仍然可以点击.header?如果我将z-index: -1 设置为.header,我可以在将光标悬停在.header 上时滚动,但它不再可点击。

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;
}

【问题讨论】:

  • 据我所知,这是不可能的,因为这是处理鼠标/滚动事件的方式。但是,我可能会想到一个基于 JS 的解决方案,尽管它相当复杂。
  • 收听mousewheel并在事件处理函数中滚动article

标签: javascript css z-index absolute


【解决方案1】:

如果您想要 CSS 解决方案,则没有 - 这是因为鼠标事件与项目对指针/光标的可见性直接相关:例如如果将.header 放在后面使其无法访问(这样article 上的滚动事件就会被触发),它也不会注册点击事件。

基于 JS 的解决方案是监听 mousewheel() 事件(this plugin,也可作为 CDN-hosted plugin 使用),然后手动触发 article 元素上的滚动。但是,这不会复制单个操作系统上的默认滚动行为,并且在具有平滑滚动事件的操作系统(如 OS X)上可能会出现断断续续的情况。

事不宜迟:

// 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!');
});

这是概念验证 JSFiddle:http://jsfiddle.net/teddyrised/CK7z8/2/

警告:如果有多个 .header 元素针对同一页面上的多个 article 元素,您将必须遍历每个 .header-article 对和为每一对分别缓存fromTop

【讨论】:

    猜你喜欢
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    相关资源
    最近更新 更多