Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

javascript - Crossing over to new elements during touchmove

I'd like to make it so that as you drag your finger over a set of elements, the background of the one you've got your finger on changes.

It seems like I want to use the touchmove event for this, but as far as I can tell the target element never changes, even as you drag around. The clientX and clientY do change, and I found this document.elementFromPoint function that works in chrome, but seems very roundabout (plus I'm not sure which browsers support it)

See this fiddle, I want the boxes to turn green as you touch through them:

http://jsfiddle.net/QcQYa/9/

By the way, in chrome, you'll need to go into the user agent tab of the inspector config modal and choose "emulate touch events" to see my example.

Edit: I found an idea to use mouseenter here How to detect html elements on touchmove and got it to work on desktop chrome, but not on mobile safari.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I took a different approach:

Every touch event I check if the touch position is inside a $('.catch') object.

function highlightHoveredObject(x, y) {
    $('.catch').each(function() {
      // check if is inside boundaries
      if (!(
          x <= $(this).offset().left || x >= $(this).offset().left + $(this).outerWidth() ||
          y <= $(this).offset().top  || y >= $(this).offset().top + $(this).outerHeight()
      )) {

        $('.catch').removeClass('green');
        $(this).addClass('green');
      }
    });
}

You can see it working on jsFiddle.
It works on Chrome, I hope it also does on mobile devices.

Edit:
In this fiddle I used both versions, mine and that one from the link in the comments (document.elementFromPoint – a jQuery solution), both seem to work on my Android phone. I also added a quick and dirty benchmark (see console) and as expected document.elementFromPoint is a few thousandth faster, if that is your concern you should check the support of document.elementFromPoint for the browsers you want to support.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...