18

至少当您在 mac 上滚动到边缘时,您会看到页面向下移动并在其后面留下纯色。我发现你可以通过设置背景颜色来改变颜色body。但是还有其他方法吗?因为有时我需要在顶部和底部使用不同的颜色等。

4

2 回答 2

15

我的解决方案是稍微作弊,并linear-gradient()htmlorbody标记上使用 a 来控制给定项目的分段背景颜色。

像这样的东西应该将背景分成两半并照顾现代浏览器。

background: -webkit-gradient(
    linear,
    left top,
    left bottom,
    color-stop(0.5, #8BC63E),
    color-stop(0.5, #EEEEEE)
);
background: -o-linear-gradient(bottom, #8BC63E 50%, #EEEEEE 50%);
background: -moz-linear-gradient(bottom, #8BC63E 50%, #EEEEEE 50%);
background: -webkit-linear-gradient(bottom, #8BC63E 50%, #EEEEEE 50%);
background: -ms-linear-gradient(bottom, #8BC63E 50%, #EEEEEE 50%);
background: linear-gradient(to bottom, #8BC63E 50%, #EEEEEE 50%);

动画 GIF 显示超出页面范围的滚动

我在 iOS 上获得相同行为的运气好坏参半,而且似乎更依赖于特定的布局。

于 2015-06-25T16:50:31.667 回答
7

我需要实现类似的东西。

@tksb 发布的解决方案在 Chrome(OS X)上对我不起作用,似乎 Chrome 使用background-color来定义橡皮筋背景,并忽略background-image.

我找到的解决方案是使用一点 JS

// create a self calling function to encapsulate our code
(function(document, window) {
  // define some variables with initial values
  var scrollTop   = 0;
  var timeout  = null;
  
  // this function gets called when you want to
  //reset the scrollTop to 0
  function resetScrollTop() {
    scrollTop = 0;
  }

  // add an event listener to `body` on mousewheel event (scroll)
  document.body.addEventListener('mousewheel', function(evt) {
    // on each even detection, clear any previous set timer
    // to avoid double actions
    timeout && window.clearTimeout(timeout);
    
    // get the event values
    var delta = evt.wheelDelta;
    var deltaX = evt.deltaX;

    // add the amount of vertical pixels scrolled
    // to our `scrollTop` variable
    scrollTop += deltaX;
    
    console.log(scrollTop);
    
    // if user is scrolling down we remove the `scroll-up` class
    if (delta < 0 && scrollTop <= 0) {
      document.body.classList.remove('scroll-up');
    }
    // otherwise, we add it
    else if (delta > 0 && scrollTop > 0) {
      document.body.classList.add('scroll-up');
    }
    
    // if no wheel action is detected in 100ms,
    // we reset our `scrollTop` variable
    timeout = window.setTimeout(resetScrollTop, 100);
  });
})(document, window);
body {
  margin: 0;
}
body.scroll-up {
  background-color: #009688;
}
section {
  min-height: 100vh;
  background-color: #fff;
}
header {
  height: 100px;
  background-color: #009688;
  color: #fff;
}

    
<section id="section">
  <header>
    this demo works only on full-screen preview
  </header>
</section>

这里有一个全屏演示来测试它: http ://s.codepen.io/FezVrasta/debug/XXxbMa

于 2016-02-05T11:17:37.560 回答