mousedown и touchstart не регистрируются на мобильных устройствах - PullRequest
0 голосов
/ 13 сентября 2018

Я создал следующий простой слайдер сравнения изображений - , модифицированный по сравнению с версией на w3schools (я знаю свою ошибку при использовании их кода).

Все это отлично работает на рабочем столе, но когда я пытаюсь использовать его на мобильном телефоне, ничего не происходит - он даже не регистрирует console.log в mousedown / touchstart (когда я нажимаю на кнопку слайдерапальцем)

(() => {
  $.fn.imageComparisonSlider = function() {
    var returnValue = this.each((index, item) => {
      var $container = $(this);
      var $overlay = $container.find('.image-comparison-slider__bottom-image');
      var $slider = $('<span class="image-comparison-slider__slider"></span>');
      var $window = $(window);

      var touchStarted = false;
      var width = $container.outerWidth();

      $container.prepend($slider);

      $container.on('mousedown touchstart', '.image-comparison-slider__slider', event => {
        event.preventDefault();
        console.log('touchstart');
        touchStarted = true;
      });

      $window.on("mousemove touchmove", windowEvent => {
        if (touchStarted) {
          // get the cursor's x position:
          let pos = getCursorPos(windowEvent);

          // prevent the slider from being positioned outside the image:
          if (pos < 0) pos = 0;
          if (pos > width) pos = width;

          // execute a function that will resize the overlay image according to the cursor:
          slide(pos);
        }
      });

      $window.on('mouseup touchend', event => {
        event.preventDefault();
        touchStarted = false;
      });

      function getCursorPos(e) {
        var thisEvent = e || window.event;

        // calculate the cursor's x coordinate, relative to the image
        return thisEvent.pageX - $container.offset().left;
      }

      function slide(x) {
        // set the width of the overlay
        $overlay.width(width - x);

        // position the slider
        $slider[0].style.left = x + 'px';
      }

      function resetSlider() {
        $overlay.width('50%');
        $slider[0].style.left = $overlay.width() + 'px'
        width = $container.outerWidth();
      }
    });

    return returnValue;
  };
})($);


$('.image-comparison-slider__container').imageComparisonSlider();
.image {
  display: block;
  width: 100%;
}

.image-comparison-slider__title {
  text-align: center;
}

.image-comparison-slider__container,
.image-comparison-slider__image-holder {
  position: relative;
}

.image-comparison-slider__bottom-image {
  position: absolute;
  overflow: hidden;
  top: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
  width: 50%;
}

.image-comparison-slider__caption {
  position: absolute;
  padding: 1rem;
  color: white;
  background: rgba(0, 0, 0, 0.6);
  z-index: 2;
  white-space: nowrap;
}

.image-comparison-slider__top-image .image-comparison-slider__caption {
  top: 0;
  left: 0;
}

.image-comparison-slider__bottom-image .image-comparison-slider__caption {
  bottom: 0;
  right: 0;
}

.image-comparison-slider__image {
  display: block;
  z-index: 1;
}

.image-comparison-slider__bottom-image .image {
  position: absolute;
  right: 0;
  top: 0;
  height: 100%;
  width: auto;
}

.image-comparison-slider__slider {
  position: absolute;
  z-index: 3;
  cursor: ew-resize;
  /*set the appearance of the slider:*/
  width: 50px;
  height: 50px;
  background-color: rgba(255, 96, 38, 0.8);
  border-radius: 50%;
  top: 50%;
  left: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  transform: translate(-50%, -50%);
}

.image-comparison-slider__slider:after {
  content: "< >";
  color: white;
  font-weight: bold;
  font-size: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="image-comparison-slider__container">
  <div class="image-comparison-slider__image-holder image-comparison-slider__top-image">
    <img src="https://www.fillmurray.com/g/400/300" alt="A test image 1" class="image">
    <div class="image-comparison-slider__caption">Left Image</div>
  </div>
  <div class="image-comparison-slider__image-holder image-comparison-slider__bottom-image">
    <img src="https://www.fillmurray.com/400/300" alt="A test image 2" class="image">
    <div class="image-comparison-slider__caption">Right Image</div>
  </div>
</div>

Скользящая ссылка для кода

1 Ответ

0 голосов
/ 13 сентября 2018

Хорошо, удалось это исправить - касание не регистрировалось из-за преобразования, поэтому я изменил это и просто использовал отрицательное поле, поскольку кнопка была фиксированного размера.

Затем я должен был исправить thisEvent.pageX для Android - поэтому сделал проверку с помощью isNaN, а затем установил его на e.originalEvent.touches[0].pageX, если это правда.

Рабочая версия:

(() => {
  $.fn.imageComparisonSlider = function() {
    var returnValue = this.each((index, item) => {
      var $container = $(this);
      var $overlay = $container.find('.image-comparison-slider__bottom-image');
      var $slider = $('<span class="image-comparison-slider__slider"></span>');
      var $window = $(window);

      var touchStarted = false;
      var width = $container.outerWidth();

      $container.prepend($slider);

      $container.on('mousedown touchstart', '.image-comparison-slider__slider', event => {
        event.preventDefault();
        console.log('touchstart');
        touchStarted = true;
      });

      $window.on("mousemove touchmove", windowEvent => {
        if (touchStarted) {
          // get the cursor's x position:
          let pos = getCursorPos(windowEvent);

          // prevent the slider from being positioned outside the image:
          if (pos < 0) pos = 0;
          if (pos > width) pos = width;

          // execute a function that will resize the overlay image according to the cursor:
          slide(pos);
        }
      });

      $window.on('mouseup touchend', event => {
        event.preventDefault();
        touchStarted = false;
      });

      function getCursorPos(e) {
        var thisEvent = e || window.event;

        let xVal = thisEvent.pageX;
        
        if (isNaN(xVal)) {
          xVal = e.originalEvent.touches[0].pageX;
        }
        
        // calculate the cursor's x coordinate, relative to the image
        return xVal - $container.offset().left;
      }

      function slide(x) {
        // set the width of the overlay
        $overlay.width(width - x);

        // position the slider
        $slider[0].style.left = x + 'px';
      }

      function resetSlider() {
        $overlay.width('50%');
        $slider[0].style.left = $overlay.width() + 'px'
        width = $container.outerWidth();
      }
    });

    return returnValue;
  };
})($);


$('.image-comparison-slider__container').imageComparisonSlider();
.image {
  display: block;
  width: 100%;
}

.image-comparison-slider__title {
  text-align: center;
}

.image-comparison-slider__container,
.image-comparison-slider__image-holder {
  position: relative;
}

.image-comparison-slider__bottom-image {
  position: absolute;
  overflow: hidden;
  top: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
  width: 50%;
}

.image-comparison-slider__caption {
  position: absolute;
  padding: 1rem;
  color: white;
  background: rgba(0, 0, 0, 0.6);
  z-index: 2;
  white-space: nowrap;
}

.image-comparison-slider__top-image .image-comparison-slider__caption {
  top: 0;
  left: 0;
}

.image-comparison-slider__bottom-image .image-comparison-slider__caption {
  bottom: 0;
  right: 0;
}

.image-comparison-slider__image {
  display: block;
  z-index: 1;
}

.image-comparison-slider__bottom-image .image {
  position: absolute;
  right: 0;
  top: 0;
  height: 100%;
  width: auto;
}

.image-comparison-slider__slider {
  position: absolute;
  z-index: 3;
  cursor: ew-resize;
  width: 50px;
  height: 50px;
  background-color: rgba(255, 96, 38, 0.8);
  border-radius: 50%;
  top: 50%;
  left: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: -25px 0 0 -25px;
}

.image-comparison-slider__slider:after {
  content: "< >";
  color: white;
  font-weight: bold;
  font-size: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="image-comparison-slider__container">
  <div class="image-comparison-slider__image-holder image-comparison-slider__top-image">
    <img src="https://www.fillmurray.com/g/400/300" alt="A test image 1" class="image">
    <div class="image-comparison-slider__caption">Left Image</div>
  </div>
  <div class="image-comparison-slider__image-holder image-comparison-slider__bottom-image">
    <img src="https://www.fillmurray.com/400/300" alt="A test image 2" class="image">
    <div class="image-comparison-slider__caption">Right Image</div>
  </div>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...