简体   繁体   中英

Adapting img src change on mouseover to touch screen devices

I'm using mouseover / mouseout and data-src / data-hover for graphic links that change an <img> src on hover.

How can I adapt the code to be touch friendly? Is there a cleaner/simpler way to implement the same functionality? I have already tried vmouseover with jQuery Mobile, and it didn't work.

I'm not using CSS :hover , because it's a specific graphic that must change color on rollover, and so I cannot use that as a starting point.

HTML setup for each link:

<a href="/books">
  <img id="book" class="image image-3" data-hover="/assets/graphics/ro-book@2x.png" data-src="/assets/graphics/book@2x.png">
</a>

Script:

$(".image-3").mouseover(function() {
  $(this).attr('src', $(this).data("hover"));
}).mouseout(function() {
  $(this).attr('src', $(this).data("src"));
});

Don't forget you should be using touch events instead of mouse events for mobile devices.

I would suggest using the touchstart event.

$(".image-3").touchstart(function() {
  $(this).attr('src', $(this).data("hover"));
}).touchend(function() {
  $(this).attr('src', $(this).data("src"));
});

This worked finally, not sure what the syntax change did but I'm satisfied.

$('.image-3').bind('touchstart touchend', function(e) {
    $(this).attr('src', $(this).data("hover"));
});

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