"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Implement Scrolling Inside an iFrame on Mobile Safari?

How to Implement Scrolling Inside an iFrame on Mobile Safari?

Published on 2024-11-12
Browse:231

How to Implement Scrolling Inside an iFrame on Mobile Safari?

Displaying iFrames in Mobile Safari

When attempting to embed an iFrame within a mobile web application using Safari on iOS devices, one common challenge arises: restricting the iFrame's dimensions to fit the iPhone screen. Height and width attributes within the iFrame element often have no effect.

However, a simple solution lies in enclosing the iFrame within a div element. This allows for the control of the iFrame's size, but it raises a new issue: the inability to scroll within the iFrame.

To address this issue, execute the following steps:

  1. Wrap the iFrame in a div with a specified height and width to constrain its dimensions.
  2. Within the iFrame content, implement JavaScript to communicate with the enclosing div's parent.
  3. Add a touch event listener to the iFrame body to capture touch events and update the parent's scroll position accordingly.

Below is an example of the JavaScript and HTML code to achieve this:

// JavaScript
setTimeout(function () {
  var startY = 0;
  var startX = 0;
  var b = document.body;
  b.addEventListener("touchstart", function (event) {
    parent.window.scrollTo(0, 1);
    startY = event.targetTouches[0].pageY;
    startX = event.targetTouches[0].pageX;
  });
  b.addEventListener("touchmove", function (event) {
    event.preventDefault();
    var posy = event.targetTouches[0].pageY;
    var h = parent.document.getElementById("scroller");
    var sty = h.scrollTop;

    var posx = event.targetTouches[0].pageX;
    var stx = h.scrollLeft;
    h.scrollTop = sty - (posy - startY);
    h.scrollLeft = stx - (posx - startX);
    startY = posy;
    startX = posx;
  });
}, 1000);

Please note that if you do not control the iFrame content, you can implement an overlay instead. However, this solution will not allow interaction with the iFrame's content, apart from scrolling.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3