简体   繁体   中英

“Paint” html table `td` elements on mobile web app

I'm working on a web application where the user needs to look at a grid of months and select whether documentation exists for a list of objects.

For the sake of user experience, I want to provide the ease of "painting" the grid. So say if the user knows the documentation exists for the whole year, she can just drag her finger across that row and every <td> in that row will have a class applied to it.

From what I can tell from Chrome Dev tools, I can get a lot of events firing when I attach a touchmove listener to each <td> , but the event's target is always the element the touch event started on and never on any other element.

Is there any way to have each <td> respond when a user drags his finger over a table?

Unfortunately the event target is set on the touchstart event so, as you drag your finger across the screen, the same event target is used as the origin of each touchmove event.

The only way around this I can think of would be to use the touchmove event to obtain the position of the touch and then figure out which table cell that would coincide with. If all your table cells are the same dimensions within a given table, taking the position obtained from the touchmove event and dividing it by the width and height of the table would give you the answer. Here's a quick snippet to get you started (this example assumes the table's position is at the very top left of the viewport):

var _columnWidth = 40;
var _rowHeight = 20;
var touchListener = function (e) {
    var touch = e.touches[0];
    var x = touch.pageX;
    var y = touch.pageY;
    var xIndex = Math.floor(_someTable.width / x / _columnWidth);
    var yIndex  = Math.floor(_someTable.height / y / _rowHeight);
};

_someTable.addEventListener('touchmove', touchListener, false);

So, if the width of the table is 80 and the height of the table is 100, and the x and y coordinates is 42 and 67 respectively, then xIndex would yield 1 and yIndex would yield 3 (meaning the second cell from the left and the forth cell from the top using zero-based indices).

Now this is a light example and won't magically solve your problem, but it's a good place to start. Hope this helps!

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