简体   繁体   中英

React.JS onMouseOver animation failing

I've been trying to get a two image slider working with a mouseOver event in react.js. I've seen a similar component linked here: codepen.io/bradtraversy/pen/NaKxdP

The problem seems to be a huge delay with refreshing the image as well as onMouseOver events that occasionally fire with an offsetX coordinate that is way off from what it should be. Thanks for any help. A demonstration of the problem I'm experiencing is linked in the codesandbox below.

https://codesandbox.io/s/romantic-perlman-tzze4?file=/src/App.js

I can't exactly contest as to why the offsetX is acting the way it does and am unable to verify what exactly you mean by refreshing the image being slow but using your codesandbox code I replaced:

if (Math.abs(xCoor - e.nativeEvent.offsetX) >= 2)
    setXCoor(e.nativeEvent.offsetX);
console.log(e.nativeEvent.offsetX);

With:

if (Math.abs(xCoor - e.nativeEvent.clientX) >= 2)
    setXCoor(e.nativeEvent.clientX -5);
console.log(e.nativeEvent.clientX);

And I am at least able to fix the flashing when the offsetX sets back to the odd numbers.

Based on some other things I was reading while researching this, offsetX seems to provide inconsistent values randomly (as you have noticed). This answer delves into it more and may be able to help you along further setting something up that is more consistent.

I've attached an updated answer here:https://codesandbox.io/s/zealous-johnson-73myy?file=/src/App.js

This uses a ref to the underlying DOM node to access the bounding rectangle and then use the clientX method as suggested by JFoxx64 to get offset within the element itself. I think his method is also just as valid, we just discovered them at the same time. Thanks!

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