简体   繁体   中英

Use JavaScript to create an expandable overlay using a transparent image

I have various locations on my page where we serve banner ads. These ads are loaded from third party sites at run time and vary in sizes.

I am looking to add an overaly of a transparent image on each of these ads so that when someone clicks on the ad, I can trigger a click event and do some processing. My questions are:

  1. How do I use JavaScript to create these expandable overalys of transparent images
  2. If someone clicks on the transparent image, will that result in a click on the underlying ad too?

Obviously I would not want to put an image on top and then stop clicks on underlying actual ad

In answer to your questions:

First off, if the ad uses iframes from a different domain than the page, then you are much more limited in what you can do. All you could do in that case is cover the ad with a transparent object that was in your own page and when you do that, the ad will no longer receive clicks.

If the ad does not use iframes from a different domain than the page, then you have these options for your two questions:

1) You can create a transparent div with javascript and place it into the same parent as the ad. It can then be located with css positioning to be on top of the ad if that's what you're really trying to do. The details of that positioning depend upon how the ad itself is positioned. Or, if the ad is only a single div itself, you could insert a transparent div into the ad and size it so that it exactly covers all the area of the ad. The transparent object would receive the initial click, but then the click would "bubble" up to the parent which would be the ad.

2) Clicking on a transparent object that is placed above the ad will result in the click going to the transparent object first, not to the ad. The click goes to the top-most object that was clicked on, though clicks will bubble up to parent objects. So, if the ad itself is a parent object, then the click will go to the ad also.

If you just want to know about the clicks, then you may be better off just adding your own eventListener for the click on the existing ad and not inserting another layer above it. You would have to wait until the ad is present, find the correct object and insert your own eventListener (assuming the ad is not inserted using iframes from a different domain).

You could attach a click listener on the whole document and whenever the click occurs, you could check if that click was from the ads. And do your processing.

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