Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...