简体   繁体   中英

JavaScript mousewheel event to scroll page horizontally when vertical scroll

I am trying to detect when a user scrolls up or down on an fixed height element and update the element's transform: translateX CSS value accordingly to scroll the contents either to the left or two the right. However, I can't figure out how to get the proper value from the delta.

document.getElementById("list").addEventListener("wheel", myFunction);

function myFunction(event) {
  var matrix = $('.gallery-list').css('transform').split(/[()]/)[1];

  var y = parseInt(event.deltaY);
  var posX = parseInt(matrix.split(',')[4]);

  console.log(y);
  console.log(posX);
  console.log(y + posX);

  //$('.gallery-list').css('transform', 'translateX('+posX + y+'px)');
}

Here is a Codepen here: https://codepen.io/kylehagler/pen/OKxMGr

Add this to your css:

.outside {
  width: 100vw;
  height: 100vh;
  top: 0;
  left: 0;
  position: absolute;
}

Surround the gallery-list div with:

<div id="outside" class="outside">

Finally, here is the JS:

document.getElementById("outside").addEventListener("wheel", myFunction);

var total = 0;

function myFunction(event) {
  var y = parseInt(event.deltaY);

  total += y;

  $(".gallery-list").css('transform', 'translateX(' + total + 'px)');
}

Hope this helps :)

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