Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

javascript - How to display the number of pages (1/X)?

function horizontalScroll(e) {
  isHorizontal = true;
  var that = this;
  that.elementWidth = that.elementWidth || getColumnWidth(that);

  var scrollDirection = (e.wheelDeltaY) ? (0 - e.wheelDeltaY) : (e.detail),
    actualColumn = Math.round(that.scrollLeft / that.elementWidth),
    targetColumn = (scrollDirection > 0) ? actualColumn + 1 : actualColumn - 1;

  if (scrollElementToColumn(that, targetColumn)) {
    e.preventDefault();
  } else {
    isHorizontal = false;
  }
}

function horizontalClick(that, to) {
  isHorizontal = true;

  that.elementWidth = that.elementWidth || getColumnWidth(that);

  var actualColumn = Math.round(that.scrollLeft / that.elementWidth),
    targetColumn = actualColumn + to;

  if (!scrollElementToColumn(that, targetColumn)) {
    isHorizontal = false;
  }
}

function getColumnWidth(that) {
  var style = window.getComputedStyle(that, null);
  var columnWidth = parseFloat(style.columnWidth || style.MozColumnWidth || style.webkitColumnWidth);
  var columnGap = parseFloat(style.columnGap || style.MozColumnGap || style.webkitColumnGap);
  return columnWidth + columnGap;
}

function scrollElementToColumn(that, columnIndex) {
  that.elementWidth = that.elementWidth || getColumnWidth(that);

  var expectedPlaceToScroll = Math.round(columnIndex * that.elementWidth),
    distanceToScroll = Math.abs(that.scrollLeft - expectedPlaceToScroll),
    defaultScrollShift = 30,
    savedScrollLeft = that.scrollLeft,
    scrollShift = (defaultScrollShift < distanceToScroll) ? defaultScrollShift : distanceToScroll;

  if (that.scrollLeft < expectedPlaceToScroll) {
    that.scrollLeft = that.scrollLeft + scrollShift;
  } else if (that.scrollLeft > expectedPlaceToScroll) {
    that.scrollLeft = that.scrollLeft - scrollShift;
  }

  if (that.scrollLeft !== expectedPlaceToScroll && savedScrollLeft !== that.scrollLeft) {
    that.actuallyMoving = setTimeout(function() {
      scrollElementToColumn(that, columnIndex)
    }, 10);
    return true;
  }

  if (that.actuallyMoving) clearTimeout(that.actuallyMoving);
  return false;
}

$(document).ready(function() {
  var elems = document.getElementsByClassName('mario');
  var scx = document.getElementById('screenx');
  var i;
  for (i = 0, nb = elems.length; i < nb; i++) {
    if (elems[i].addEventListener) {
      elems[i].addEventListener("mousewheel", horizontalScroll, false); // IE9, Chrome, Safari, Opera
      elems[i].addEventListener("DOMMouseScroll", horizontalScroll, false); // Firefox
    } else elems[i].attachEvent("onmousewheel", horizontalScroll); // IE 6/7/8
  }

  $("#next").on('click', function() {
    horizontalClick(elems[0], 1);
  });

  $("#prev").on('click', function() {
    horizontalClick(elems[0], -1);
  });

  // at least 100 px are a swipe
  // you can use the value relative to screen size: window.innerWidth * .1
  const offset = 100;
  let xDown, yDown

  scx.addEventListener('touchstart', e => {
    const firstTouch = getTouch(e);

    xDown = firstTouch.clientX;
    yDown = firstTouch.clientY;
  });

  scx.addEventListener('touchend', e => {
    if (!xDown || !yDown) {
      return;
    }

    const {
      clientX: xUp,
      clientY: yUp
    } = getTouch(e);
    const xDiff = xDown - xUp;
    const yDiff = yDown - yUp;
    const xDiffAbs = Math.abs(xDown - xUp);
    const yDiffAbs = Math.abs(yDown - yUp);

    // at least <offset> are a swipe
    if (Math.max(xDiffAbs, yDiffAbs) < offset) {
      return;
    }

    if (xDiffAbs > yDiffAbs) {
      if (xDiff > 0) {
        horizontalClick(elems[0], -1);
      } else {
        horizontalClick(elems[0], 1);
      }
    } else {
      if (yDiff > 0) {
        console.log('up');
      } else {
        console.log('down');
      }
    }
  });

  window.addEventListener('keydown', function(e) {
    switch (e.which) {
      case 37: // left
        horizontalClick(elems[0], -1);
        break;

      case 39: // right
        horizontalClick(elems[0], 1);
        break;

      default:
        return; // exit this handler for other keys
    }

    e.preventDefault(); // prevent the default action (scroll / move caret)
  });

  window.addEventListener('resize', function(e) {
    console.log('resizing, i saw you !');
    for (i = 0, nb = elems.length; i < nb; i++) {
      elems[i].elementWidth = getColumnWidth(elems[i]);
    }
  });
});

function getTouch(e) {
  return e.changedTouches[0]
}
@import url(https://fonts.googleapis.com/css?family=Montserrat);
html,
body {
  overflow: hidden;
}

.background {
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center center;
  overflow: hidden;
  will-change: transform;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
  height: 130vh;
  position: fixed;
  width: 100%;
  -webkit-transform: translateY(30vh);
  transform: translateY(30vh);
  transition: all 1.2s cubic-bezier(0.22, 0.44, 0, 1);
}

.background:first-child {
  -webkit-transform: translateY(-15vh);
  transform: translateY(-15vh);
}

.background:first-child .content-wrapper {
  -webkit-transform: translateY(15vh);
  transform: translateY(15vh);
}

.background:nth-child(1) {
  z-index: 3;
}

.poscustomtext {

  display: flex;
  justify-content: center;
  align-items: center;
}

.background:nth-child(3) {
  z-index: 1;
}

.content-wrapper {
  height: 100vh;
  display: flex;
  justify-content: center;
  text-align: center;
  flex-flow: column nowrap;
  color: #fff;
  font-family: Montserrat;
  text-transform: uppercase;
  -webkit-transform: translateY(40vh);
  transform: translateY(40vh);
  will-change: transform;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
  transition: all 1.7s cubic-bezier(0.22, 0.44, 0, 1);
}

.content-title {
  font-size: 12vh;
  line-height: 1.4;
}

.background.up-scroll {
  -webkit-transform: translate3d(0, -15vh, 0);
  transform: translate3d(0, -15vh, 0);
}

.background.up-scroll .content-wrapper {
  -webkit-transform: translateY(15vh);
  transform: translateY(15vh);
}

.background.up-scroll+.background {
  -webkit-transform: translate3d(0, 30vh, 0);
  transform: translate3d(0, 30vh, 0);
}

.background.up-scroll+.background .content-wrapper {
  -webkit-transform: translateY(30vh);
  transform: translateY(30vh);
}

.background.down-scroll {
  -webkit-transform: translate3d(0, -130vh, 0);
  transform: translate3d(0, -130vh, 0);
}

.background.down-scroll .content-wrapper {
  -webkit-transform: translateY(40vh);
  transform: translateY(40vh);
}

.background.down-scroll+.background:not(.down-scroll) {
  -webkit-transform: translate3d(0, -15vh, 0);
  transform: translate3d(0, -15vh, 0);
}

.background.down-scroll+.background:not(.down-scroll) .content-wrapper {
  -webkit-transform: translateY(15vh);
  transform: translateY(15vh);
}

#prev {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: rgba(255, 235, 59, 0.75);
  cursor: pointer;
  position: absolute;
  left: 0;
  top: calc(50% - 50px);
  z-index: 9;
}

#next {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: rgba(255, 235, 59, 0.75);
  cursor: pointer;
  position: absolute;
  right: 0;
  top: calc(50% - 50px);
  z-index: 9;
}

article.mario {
  height: 80vh;
  width: calc(80vw - 0px);
  column-width: calc(80vw - 0px);
  column-gap: calc(5vw + 0px);
  column-rule: 2px dotted #ddd;
  overflow: hidden;
  border: solid 8px black;
}

article.mario:hover {
  border: solid 8px gold;
}

.customtext {
  padding-top: 0px;
  padding-right: 40px;
  padding-bottom: 0px;
  padding-left: 40px;
  text-align: justify;
}
<section class="background" id="screenx">
  <div class="content-wrapper">
    <div class="poscustomtext">
      <div id="prev"></div>
      <div id="next"></div>
      <article class="mario">
        <div class="customtext">
          <div style="box-sizing: inherit; color: #555555; font-family: Helvetica, sans-serif, Ariel; font-size: 16px; font-weight: 400;">
            <a href="http://vfl.ru/fotos/abca98b122166092.html" target="_blank" rel="noreferrer noopener" style="box-sizing: inherit; background-color: transparent; color: #2fb5d2; text-decoration-line: none; touch-action: manipulation;"><img src="http://images.vfl.ru/ii/1529362396/abca98b1/22166092_m.jpg" border="0" alt="user posted image" style="box-sizing: inherit; border-style: none; vertical-align: middle; margin-left: auto; margin-right: auto; display: block; max-width: 100%; height: auto;"></a>
          </div>
          <p style="box-sizing: inherit; margin-top: 0px; margin-bottom: 1rem; font-size: 0.9375rem; color: #7a7a7a; font-weight: 400; font-family: Helvetica, sans-serif, Ariel;"><br style="box-sizing: inherit;"><br style="box-sizing: inherit;"><span style="box-sizing: inherit;">В ту пору, когда&nbsp;</span><span style="box-sizing: inherit; font-weight: bolder;">Headhunter</span><span style="box-sizing: inherit;">&nbsp;была анонсирована, мода на стелс-экшены только-только начинала зарождаться, и любой мало-мальски приличный проект, хоть как-то позволяющий игроку бесшумно расправляться с неприятелями, сразу же нарекали “слелсом” и сталкивали лоб в лоб с&nbsp;</span>
            <span
              style="box-sizing: inherit; font-weight: bolder;">Metal Gear Solid</span><span style="box-sizing: inherit;">.</span><br style="box-sizing: inherit;"><br style="box-sizing: inherit;"><span style="box-sizing: inherit;">Это только потом выяснится, что в&nbsp;</span><span style="box-sizing: inherit; font-weight: bolder;">Headhunter</span>
              <span
                style="box-sizing: inherit;">&nbsp;вообще-то есть много и от&nbsp;</span><span style="box-sizing: inherit; font-weight: bolder;">Resident Evil</span><span style="box-sizing: inherit;">, и даже от&nbsp;</span><span style="box-sizing: inherit; font-weight: bolder;">Driver</span>
                <span
                  style="box-sizing: inherit;">. Да и сама по себе боевая система, включая знаменитую (да-да, ту самую, что позже будет популяризована не без помощи&nbsp;</span><span style="box-sizing: inherit; font-weight: bolder;">Resident Evil 4</span><span style="box-sizing: inherit;">) камеру из-за плеча, куда ближе к&nbsp;</span>
                  <span
                    style="box-sizing: inherit; font-weight: bolder;">Syphon Filter</span><span style="box-sizing: inherit;">, нежели детищу&nbsp;</span><span style="box-sizing: inherit; font-weight: bolder;">Konami</span><span style="box-sizing: inherit;">. Но маркетинг ведь - штука сродни эпидемии: что надуют в ушко - в то и уверуешь.</span>
                    <br
                      style="box-sizing: inherit;"><br style="box-sizing: inherit;"><span style="box-sizing: inherit;">И все было бы ничего, кабы датой релиза не значился конец 2001-го, а в качестве целевой платформы не был бы выбран Dreamcast. Тут даже к Ванге не ходи, чтобы понять всю абсурдность подобного

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I made a codepen with your code examples here:

https://codepen.io/dschenk/pen/eoRooz

(codepens like this help other people look at and debug code more easily)

I started with an implemention of the page-number counter you asked for. There are basically four things you need to do:

  • Have an element in the HTML where the page-counter will be
  • Initially set the current-page number and the amount of pages there are.
  • Update the current-page whenever the content-window is changed.
  • Update the amount of total pages when the window is resized.

To accomplish this you can create two basic functions:

function setAmountOfPages(amountOfPages) {
    $(".page-number > .page-amount").html(amountOfPages);
}

function setCurrentPageNumber(currentPageNumber) {
  $(".page-number > .page-current").html(currentPageNumber);
}

Now you need to call them at the right time with the right argument.

I hope this serves as a starting point for you.

(There is a bug present: when one clicks very fast, you can get the current-page to show "0/8". This happens because of the timing functions)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...