How can you make an iframe have pointer-events: no

2019-02-11 15:34发布

问题:

I have an iframe with an inherited pointer-events: none; but when I have inserted a <div> inside the iframe with a pointer-events: auto; the div won't react to clicks or any mouse hover events.

The reason for this is that the iframe is inside a <div style="position:fixed;"> so it is kind of like a little menu. but I would like the user to click through the iframe, but not through the links and divs in the iframe.

And yes, it absolutely needs to remain an iframe.

How could I bypass this? Can I even bypass this?

Here's a simple example: jsfiddle.net/MarcGuiselin/yLo119sw/2

回答1:

You're working with position:absolute, according to the example you've uploaded on jsfiddle... Adding a z-index to the "you can't click me because i'm behind the iframe" button allows me to click it.

Z-Index

EDIT: If you want to do a pointer-events: none; everywhere except in one div, you can add the pointer-events in each element instead of the iframe. According to your example in the fiddle, if you want to save the Nicholas Cage but block the other events, you can do something like this:

switchbutton.onclick=function(){
   this.innerHTML="reload to reset";
   //iframe.style.pointerEvents="none";
   cantclick.innerHTML="You can click me now! :)";
   iframe.contentDocument.body.innerHTML="<button>You can't click me now because my parent iframe is click-through! :(</button><br>or save this gorgeous image of your favorite actor which may or may not be relavant to the problem.<br><img id='nicholasCage' src='http://media2.popsugar-assets.com/files/2014/01/06/008/n/1922283/131b4126c7b8738f_thumb_temp_image333458751389045360.jpg.xxxlarge/i/Best-Nicolas-Cage-Memes.jpg'/>";

   var iframeBody = iframe.contentDocument,
       elements = iframeBody.querySelectorAll("*"),
       i,
       len = elements.length;

   for(i=0;i<len;i++){
       elements[i].style.pointerEvents="none";
   }

   iframeBody.getElementById("nicholasCage").style.pointerEvents="all";
}

If you can use jQuery you can do it faster just using $("iframe *").css("pointer-events","none");



回答2:

Don't give the whole iframe pointer-events: none. Just inside the iframe put a CSS rule body * { pointer-events: none;}

This way the iframe does not block events, however elements inside the iframe are not clickable.



回答3:

Have you tried this?

pointer-events: inherit;

I know you already got your answer, but I thought this might work, too.



标签: html css iframe