There is a table with the same pictures depicting a switch.

function on() { alert('Switch ON'); } function off() { alert('Switch OFF'); } 
 <map name=swm> <area shape=rect coords="0,0,40,40" href="javascript:on()" alt="on"> <area shape=rect coords="0,40,40,80" href="javascript:off()" alt="off"> </map> <table> <tr><th colspan=2>ΠŸΡ€Π°Π²Ρ‹ΠΉ Π²Ρ‹ΠΊΠ»ΡŽΡ‡Π°Ρ‚Π΅Π»ΡŒ</tr> <tr><td class=dev><img src='sw.png' usemap='#swm' width=80 height=80></td> <td><code>↓</code><small>2015-12-10</small></tr> <tr><th colspan=2>Π‘Ρ€Π΅Π΄Π½ΠΈΠΉ Π²Ρ‹ΠΊΠ»ΡŽΡ‡Π°Ρ‚Π΅Π»ΡŒ</tr> <tr><td class=dev><img src='sw.png' usemap='#swm' width=80 height=80></td> <td><code>↑</code><small>08:55:33</small></tr> <tr><th colspan=2>Π›Π΅Π²Ρ‹ΠΉ Π²Ρ‹ΠΊΠ»ΡŽΡ‡Π°Ρ‚Π΅Π»ΡŒ</tr> <tr><td class=dev><img src='sw.png' usemap='#swm' width=80 height=80></td> <td><code>↑</code><small>08:55:33</small></tr> <tr><th colspan=2>ΠšΠΎΠΌΠΏΠ»Π΅ΠΊΡ‚ Π΄Π°Ρ‚Ρ‡ΠΈΠΊΠΎΠ²</tr> <tr><td class=dev><img src='sn.png' width=80 height=80></td> <td><em>100lx</em><br> <em>20Β°C</em><br> <small>14:48:06</small></tr> </table> 

Is it possible, without reproducing a card for each picture, to distinguish which picture was clicked?

    1 answer 1

    You can exclude the use of the map and check the coordinates of the click.

     document.addEventListener('click', function(e) { var img = e.target, x; if (img.tagName !== 'IMG') return; // ΠšΠΎΠΎΡ€Π΄ΠΈΠ½Π°Ρ‚Ρ‹ Ρ‚ΠΎΡ‡ΠΊΠΈ Π½Π° ΠΊΠ°Ρ€Ρ‚ΠΈΠ½ΠΊΠ΅ Π½Π° ΠΊΠΎΡ‚ΠΎΡ€ΡƒΡŽ ΠΊΠ»ΠΈΠΊΠ½ΡƒΠ»ΠΈ x = (e.layerX == undefined ? e.offsetX : e.layerX) - img.getBoundingClientRect().left; // ΠŸΡ€ΠΎΠ²Π΅Ρ€ΡΠ΅ΠΌ ΠΏΡ€ΠΈΠ½Π°Π΄Π»Π΅ΠΆΠ½ΠΎΡΡ‚ΡŒ ΠΊ классу if (img.classList.contains('left') && x < img.offsetWidth / 2) { alert('ΠšΠ»ΠΈΠΊΠ½ΡƒΠ»ΠΈ ΠΏΠΎ Π»Π΅Π²ΠΎΠΉ части ΠΊΠ°Ρ€Ρ‚ΠΈΠ½ΠΊΠΈ:' + img.alt); } else if (img.classList.contains('right') && x > img.offsetWidth / 2) { alert('ΠšΠ»ΠΈΠΊΠ½ΡƒΠ»ΠΈ ΠΏΠΎ ΠΏΡ€Π°Π²ΠΎΠΉ части ΠΊΠ°Ρ€Ρ‚ΠΈΠ½ΠΊΠΈ:' + img.alt); } }); 
     <img src="" class="left" alt="ΠšΠ°Ρ€Ρ‚ΠΈΠ½ΠΊΠ° 1 (лСвая)" width="100" height="100" /> <img src="" class="left" alt="ΠšΠ°Ρ€Ρ‚ΠΈΠ½ΠΊΠ° 2 (лСвая)" width="100" height="100" /> <img src="" class="right" alt="ΠšΠ°Ρ€Ρ‚ΠΈΠ½ΠΊΠ° 3 (правая)" width="100" height="100" /> 

    • offsetX sometimes works incorrectly, replaced on clientX - sercxjo