How to get a reference to the IMG element from MAP

2019-09-14 23:57发布

问题:

Say we have an IMG (idless) element which has an usemap="#hotmap" attribute. Then we have this <MAP name="hotmap"> element (in the BODY) containing an enormous amount of AREAs (say >1000). It's obvious, that we'd like to delegate the eventhandling of AREAs to the MAP element instead of creating hundreds of eventlisteners.

Now in the eventhandler function (for MAP) we'd like to get a reference to the IMG which uses the MAP which fired the event. However, MAP is in the BODY and IMG element can't have HTML, thus MAP can't be among its children. So the question is, how can we catch the IMG in this eventhandler?

A trivial example:

<img src="some_image.png" usemap="#hotmap" />
                ...
<map id="map" name="hotmap">
    <area shape="circle" coords="100,100,50" />
                ...
</map>

map.addEventListener('click', function (e) {
    var area = e.target,
        image = ?; // How to refer the img
        ...
}, false);

Side notes

I'm working on a HTA project where I need an object which dynamically creates and assigns hotmaps for images which have certain custom attributes. This object gets its data for AREAs from external file, and everything is working fine, except this one little detail. For now, I'm adding a custom property containing a reference to the "user" IMG, to each AREA. Though this would be unnecessary, if it could be done only once in the eventhandler.

EDIT

A live demo at jsFiddle, (not HTA included, works in any(?) modern browser)


EDIT II

I just realized, that I can't reuse the MAP, since it can be also resized according to the IMG. So I've put the reference to the IMG to the MAP instead of its AREAs.

Though this solved my problem, I'd still like to know, how to get the IMG in the eventhandler, just in general. The suggested querySelector() solution seems not work (tumbled with it earlier, now it returns undefined)

回答1:

At first:
Be careful with the methods you use there, HTA by default runs with IE7(standards-mode content) or IE5(quirks-mode content), so you can't rely on features that are available in your IE. I would suggest to use only methods that are available in IE5, e.g. use attachEvent instead of addEventListener.

Following this article you should be able to define the compatibility, but for me it doesn't work.

Related to the question:

Instead of observing the click-event of the map, observe the click on the img.
When you observe the click on the map, and the map is used by multiple images, there is no way to find a relation between the map and the image.