为什么代码“水平循环滚动”在真正的浏览器上不起作用?

时间:2019-07-04 08:43:09

标签: javascript html css

我应该使水平循环的组件在两个方向上滚动。

当我将它们放在单个HTML文件中时,在Codepen上完全可以,但在真正的浏览器上却不能。向上但向下都可以。

我在几种浏览器上都尝试过,但是结果是一样的。

您可以在此处查看完整的源代码:

HTML

<div id="page">
    <div class="pane">
        <div>Looping Horizontal Scroll</div>
    </div>
    <div class="pane">
        <div>2</div>
    </div>
    <div class="pane">
        <div>3</div>
    </div>
    <div class="pane">
        <div>4</div>
    </div>
    <div class="pane">
        <div>5</div>
    </div>
    <div class="pane">
        <div>Last</div>
    </div>
    <div class="pane">
        <div>Looping Horizontal Scroll</div>
    </div>
</div>

CSS

body{
  overflow-x:hidden;
  color:#FFF;
  font-family:Helvetica;
  font-size:200%;
}
#page {
  overflow:hidden;
  white-space:nowrap;
  position:fixed;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background-color:#CCC;
  display:flex;
  flex-wrap:no-wrap;
}
.pane {
  flex:0 0 100vw;
  height:100vh;
  display:flex;
  position:relative;
  align-items:center;
  justify-content:center;
  background-color: #45CCFF;
}

.pane:nth-child(4n+2)  {
  background-color: #49E83E;
}
.pane:nth-child(4n+3)  {
  background-color: #EDDE05;
}
.pane:nth-child(4n+4)  {
  background-color: #E84B30;
}
.pane:last-child {
  background-color: #45CCFF;
}

脚本

var page = document.getElementById('page');
var last_pane = page.getElementsByClassName('pane');
last_pane = last_pane[last_pane.length-1];
var dummy_x = null;

window.onscroll = function () {
  // Horizontal Scroll.
  var y = document.body.getBoundingClientRect().top;
  page.scrollLeft = -y;

  // Looping Scroll.
  var diff = window.scrollY - dummy_x;
  if (diff > 0) {
    window.scrollTo(0, diff);
  }
  else if (window.scrollY == 0) {
    window.scrollTo(0, dummy_x);
  }
}
// Adjust the body height if the window resizes.
window.onresize = resize;
// Initial resize.
resize();

// Reset window-based vars
function resize() {
  var w = page.scrollWidth-window.innerWidth+window.innerHeight;
  document.body.style.height = w + 'px';

  dummy_x = last_pane.getBoundingClientRect().left+window.scrollY;
}


It is supposed to work fine on any browsers.


0 个答案:

没有答案