我有一个自定义范围滑块。
但是,我遇到的问题是,我无法设法使自定义“拇指”(在本例中为🔥)的滑动在触摸设备上起作用。
这里是项目进行中:https://wagon-city-guides.herokuapp.com/spots/32
[如果您在手机上检查(我使用的是iPhone),您仍然会看到原始拇指的边框(我暂时留意了它),它可以滑动并起作用,但是火焰(自定义拇指)不会出现……虽然它对于点击设备很好用。
我仅在寻找Vanilla JS解决方案。 🙏🏽
这是我的代码:
class RatingSlider {
constructor() {
this.ratingSliderForm = document.querySelector(".js-rating-slider-form");
this.ratingSliderInput = document.querySelector(".js-rating-slider-input");
this.ratingSliderThumb = document.querySelector(".js-rating-slider-thumb");
this.ratingSliderValue = document.querySelector(".js-rating-slider-value");
this.ratingSliderIcon = document.querySelector(".js-rating-slider-icon");
this.isPressed = false;
this.moveEvent;
this.holdEvent;
this.releaseEvent;
this.bind();
}
handleSliding(event) {
if (!this.isPressed) {
return;
}
if (
event.offsetX > 0 &&
event.offsetX < this.ratingSliderInput.offsetWidth
) {
this.ratingSliderThumb.style.left = `${event.offsetX - 10}px`;
this.ratingSliderIcon.style.transform = `scale(${1 +
this.ratingSliderInput.value / 150})`;
this.ratingSliderValue.innerText = `${this.ratingSliderInput.value}°`;
}
}
setRating() {
this.ratingSliderThumb.style.left = `${(this.ratingSliderInput.offsetWidth /
100) *
this.ratingSliderInput.value -
10}px`;
this.ratingSliderIcon.style.transform = `scale(${1 +
this.ratingSliderInput.value / 150})`;
this.ratingSliderValue.innerText = `${this.ratingSliderInput.value}°`;
this.ratingSliderInput.addEventListener(
`${this.holdEvent}`,
() => (this.isPressed = true)
);
this.ratingSliderInput.addEventListener(`${this.releaseEvent}`, () => {
this.isPressed = false;
this.ratingSliderForm.submit();
});
}
setEvents() {
if ("ontouchstart" in document.documentElement) {
this.moveEvent = "touchmove";
this.holdEvent = "touchstart";
this.releaseEvent = "touchend";
} else {
this.moveEvent = "mousemove";
this.holdEvent = "mousedown";
this.releaseEvent = "mouseup";
}
}
bind() {
if (!this.ratingSliderForm) {
return;
}
this.setEvents();
this.setRating();
this.ratingSliderInput.addEventListener(`${this.moveEvent}`, event =>
this.handleSliding(event)
);
}
}
export default RatingSlider;
问题是触摸事件没有offsetX
和offsetY
属性。它们的值在移动设备中返回undefined
。因此,您需要将它们添加到事件中。
在handleSliding(event)
方法的开头,添加此:
if ("ontouchstart" in document.documentElement) {
event = addOffsetsOnTouch(event);
}
function addOffsetsOnTouch(e) {
let touch = e.touches[0] || event.changedTouches[0];
let target = document.elementFromPoint(touch.clientX, touch.clientY);
event.offsetX = touch.clientX - target.getBoundingClientRect().x;
event.offsetY = touch.clientY - target.getBoundingClientRect().y
return e;
}