Home > Web Front-end > CSS Tutorial > How to Implement Scrolling Inside an iFrame on Mobile Safari?

How to Implement Scrolling Inside an iFrame on Mobile Safari?

DDD
Release: 2024-11-11 12:39:02
Original
651 people have browsed it

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);
Copy after login
<!-- HTML -->
<div>
Copy after login

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.

The above is the detailed content of How to Implement Scrolling Inside an iFrame on Mobile Safari?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template