How can you make an iframe have pointer-events: none; but not on a div inside that?

前端 未结 5 1848
误落风尘
误落风尘 2021-01-01 10:22

I have an iframe with an inherited pointer-events: none; but when I have inserted a

inside the iframe with a pointer-events: auto
5条回答
  •  轮回少年
    2021-01-01 10:52

    I've searched a lot and figured out a workaround myself.

        // the iframe element
        const frame = document.getElementsByTagName("iframe")[0];
        frame.onload = function () {
          const frameDocument = frame.contentDocument;
          document.addEventListener("mousemove", onMouseMove, true);
          frameDocument.addEventListener("mousemove", onMouseMove, true);
    
          function onMouseMove(e) {
            let coord;
            if (e.currentTarget === document) {
              coord = {
                x: e.pageX - frame.offsetLeft,
                y: e.pageY - frame.offsetTop,
              };
            } else {
              coord = { x: e.clientX, y: e.clientY };
            }
    
            const el = frameDocument.elementFromPoint(coord.x, coord.y);
            // you can compare to your own element if needed
            frame.style.pointerEvents = !el || el === frameDocument.body ? "none" : "auto";
          }
        };
    

    The iframe will auto toggle its pointer-events and all events just works seamlessly.

提交回复
热议问题