抱歉英语不好。
这是 link网站。
我的任务是创建没有滚动的网站。当用户点击屏幕右侧部分时,汽车开始向前移动。当它到达屏幕中间时 - 汽车停下来,固定内容 block 开始向相反方向移动。如果用户将光标移动到屏幕左侧(同时按住鼠标按钮单击)汽车应该向后移动。
桌面版按预期工作。但是手机版很慢。 (它不是很慢,它不像桌面那么流畅我猜)
我该怎么做才能解决这个问题?
- 在 touchstart 事件中,我获取 event.pageX 值以检查用户触摸了屏幕的哪一部分。 (所以我会知道汽车应该朝哪个方向移动)并将这个值存储在变量“mousePos”中。然后我用移动函数调用 setInterval
- 在 touchend 事件中,我清除间隔以停止汽车移动。
- 在 touchmove 上,我将用新的 event.pageX 值重写“mousePos”变量。例如:用户单击,汽车开始移动,如果用户将光标向左移动,我将使用此变量来检查方向并让汽车返回。
- 在 mouseMove 函数中,我将检查汽车位置并决定应该执行什么操作 - 移动汽车或移动背景,我将检查它是否到达终点的起点
事件:
$(document).on('mousedown touchstart', '.mouse-click', function(event){
clicking = true;
mousePos = event.pageX;
if ( event.target.className == 'helper' ) {
showModal();
} else {
moveStuff = setInterval(mouseMove, 1);
}
});
$(document).on('mouseup touchend', function(){
clicking = false;
carLights.removeClass('blink');
clearInterval(moveStuff);
})
$(document).on('mousemove touchmove', '.mouse-click', function(event){
if(clicking == false) {
return;
} else {
mousePos = event.pageX;
}
});
功能:
function mouseMove() {
let offset = parseInt( mainContent.css('left') );
let offsetCar = parseInt( car.css('left') );
if ( mousePos > middleScreen ) {
carLights.removeClass('blink');
if ( offset < - ( contentWidth ) ) {
return;
} else {
rotateWheelsForward();
if ( offsetCar < middleScreen ) {
car.css('left', (offsetCar + mouseSpeed) + 'px');
} else {
mainContent.css('left', (offset - mouseSpeed) + 'px');
}
}
} else if ( mousePos < middleScreen ) {
carLights.addClass('blink');
if ( offset > 0 ) {
carLights.removeClass('blink');
return;
} else {
rotateWheelsBackward();
if ( offsetCar > minCarLeft ) {
car.css('left', (offsetCar - mouseSpeed) + 'px');
} else {
mainContent.css('left', (offset + mouseSpeed) + 'px');
}
}
}
}
那么我怎样才能让手机上的运动更顺畅呢? (我使用 iphone 5s safari,但在 iphone 6 中测试,仍然效果不佳)
我应该对此代码进行哪些更改?
最佳答案
我建议使用 transform 而不是 position eg: left, top cause that's really affect layer reflow-repaint.使用 requestAnimationFrame(明智地)执行平滑的事件动画,如滚动、鼠标弹起或任何其他事件。
然后使用 will-change: transform;
到将在未来“转换”的元素。这将创建新层并为以后的元素更改做准备。
在我的例子中,相对位置会影响渲染工具 chrome 上的回流或绿色闪烁。所以我更喜欢使用固定/绝对位置来防止这种情况。
这里有一些很棒的文章供您获取 Leaner, Meaner, Faster Animations with requestAnimationFrame以及如何to achieving 60 fps animations with css
希望这有帮助;)
关于javascript - 如何使移动设备中的 jquery setinterval 移动更顺畅?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55580775/