Php iframe height 100

Сделать так, чтобы iframe автоматически настраивал высоту в соответствии с содержимым без использования полосы прокрутки? [Дубликат]

Я хочу, чтобы он мог регулировать его высоту в соответствии с содержимым внутри него, не используя прокрутку.

Это можно сделать с помощью CSS. В CSS есть концепция, называемая медиазапросами, в которой размер контента изменяется в соответствии с размером экрана.

«Угловой . » т.е. требуется Javascript? Другими словами, нельзя делать это на межсайтовых фреймах (из-за ограничений межсайтового скриптинга), верно? Как подсказывает @ clankill3r, это демонстрирует необходимость чистого CSS-решения этой проблемы!

17 ответов

И измените ваш iframe на это:

 

Это не будет работать, если iframe содержит контент из другого домена из-за одной и той же политики происхождения , есть другой вопрос о SO с некоторыми междоменными решениями stackoverflow.com/questions/5589756/…

Решения, кажется, не работают, если содержание iframe имеет изменение высоты на js (например, слайдер)

Это еще несколько вопросов, которые необходимо учитывать: изменение содержимого в iframe, изменение размера браузера, загрузка iframe при первой проверке и междоменном домене. Я собрал небольшую библиотеку, потому что я не мог найти решение, которое охватывало бы каждую проблему. github.com/davidjbradshaw/iframe-resizer

это не полное решение, поэтому, конечно, иногда оно не может работать. Например, если iframe содержит форму, с проверкой JS, после появления блоков ошибок будет отображаться полоса прокрутки. Поэтому существует необходимость в дополнительном обработчике изменения размера, который будет запускать функцию resizeIframe.

Читайте также:  Java map for remove

Также обнаружилось, что это прекрасно работает в Chrome, но в Firefox и IE содержимое немного обрезано внизу.

К сожалению, этот метод не является надежным на 100%. Если соединение медленное, и iframe не загружается при запуске функции, высота не будет отрегулирована. Это связано с тем, что загрузка прослушивает только элементы страницы, а не содержимое iframe.

Это не работает с элементами, которые «свертываются», например, datatables или плавающие div. Высота зависит от того, какой будет нормальная развернутая высота, а не от конечной высоты.

@ hjpotter92 Это отличное решение. Я искал iframe auto fit / resizer, и это единственное, что сработало для меня (с или без div), и я много пробовал с прошлой ночи. Немного больше информации: я использую bootstrap 3, и многие другие решения JS / CSS не работали, так как не изменили бы его размер по вертикали в зависимости от содержимого, получаемого из БД. Просто хотел сказать спасибо, ура

@ hjpotter92 Приложение к моему комментарию. (Небольшая ошибка) Хотя в нижней части есть небольшое обрезание, где, например, с буквой, которая опускается ниже строки набора текста, такой как «g», его хвост обрезается, просто подумав, что вы / другие могли бы захотеть знаю и посмотрю, смогу ли я придумать решение для этого.

@ Fred-ii- Возможно, добавление дополнительного font-size к высоте объекта должно решить эту проблему.

@ hjpotter92 Да, или я видел комментарий в ответе (внутри того же вопроса) , где я изменил вашу строку так, чтобы она читалась как obj.style.height = (obj.contentWindow.document.body.scrollHeight +5) + ‘px’; который работал (для меня) прекрасно, и я могу жить с этим. Хотя, я мог бы, возможно, просто добавить дополнительную
под моей последней записью в db в php. Всегда есть способ 😉

Это только заставит iframe расти. Это никогда не уменьшится. Положите obj.style.height = 0, прежде чем читать рост.

Как вы можете видеть, теперь вы получаете iframe для ссылки test1 высотой 648px и для ссылки test2 высотой 2200px и для ссылки test3 высотой 440px и т. Д. Вы можете добавить столько ссылок, сколько захотите, используя столько размеров sizez, сколько ты хочешь. Единственным недостатком этого кода является то, что он работает только для одного iframe на странице, не более одного и родительских кодов из iframe не работают ни в одном браузере, кроме проводника. Но вы можете использовать _self, _top и _blank или имена целей. Не _parent, это не работает.

@SeekLoad Использование ссылки jsfiddle.net было бы проще =) Я обновлю свой ответ выше фрагментом кода, если бы вы могли предоставить мне пример минимальной, полной и проверяемой ссылки jsfiddle.

ПРИМЕЧАНИЕ. Я знаю, что на этот вопрос уже дан ответ, но я ПРОВЕРИЛ все ответы, и ни один из них не работал должным образом, и так, как был задан вопрос, поэтому я поиграл с кодами и нашел ответ, который работает.

@ hjpotter92 Самый простой способ сделать это, если вы спросите меня, — это просто сделать файл HTML / HTM на своем компьютере и протестировать код. Вот как я это делаю, не нужны ссылки и онлайн-эмуляторы такие. Таким образом, вы точно знаете, как и если это работает. Также советуем протестировать более чем один браузер, чтобы увидеть, работает ли он на нескольких платформах.

@ hjpotter92 Поскольку ответ на этот вопрос помечен как ответ, хотя помеченный ответ не работал должным образом, я не могу поставить другой ответ, хотя мой ответ работает правильно. Поэтому лучшее, что я могу сделать для вас, если вы хотите онлайн-эмулятор и не тестируете его на своем компьютере, — это поместить его в онлайн-эмулятор и дать вам ссылку.

@ hjpotter92 Скажите мне, что хорошего в коде, если вы проверяете его, и он проверяется, но на самом деле он не работает, выполняя свою работу на веб-странице? Мой код не может быть проверен W3, но это НЕ НУЖНО, так как важная часть заключается в том, что он работает и выполняет свою работу. Если вы можете заставить его работать и правильно выполнять работу, и в то же время проходить валидацию, я рад, что такое решение может быть принято. На данный момент я еще не нашел проверенный код, который работает правильно еще. Я предпочел бы иметь не проверенный код W3, который работает, а затем утвержденный проверенный код, который не работает.

Вот тест на codepen.io/SeekLoad/pen/yEdQBK , но вам все равно нужно скопировать его в браузер, чтобы он работал.

Источник

Iframe content exceeds 100%

Page 1: tobbar.php Solution: If you want to change iframe height to the iframe content height you need to use JavaScript: If you want to change table width inside iframe you can do that with contentWindow: So I could do the video page with an iframe which contains the page of comments and users swap pages through the iframe.

Iframe content exceeds 100%

I have page with 3 iframes, the top iframe contains a table which I would like to fit to the size of the iframe.

When I use the code below the content in the iframe exceeds 100% and the only way to view all the content is to scroll which is no practical in this case.

How would I make the table contained in the iframe fit to 100% so that all the content is displayed within the iframes height?

   
  
CredentialValue
Client MSISDN
Date of Birth
Member Since
sysUSRID
Name

If you want to change iframe height to the iframe content height you need to use JavaScript:

document.getElementById('iframe').height = document.getElementById('iframe').contentWindow.document.body.scrollHeight+'px'; 

If you want to change table width inside iframe you can do that with contentWindow:

document.getElementById('iframe').contentWindow.document.getElementById('table').style.width = '100%'; 

Php — Getting iframe content in script like a browser, I wanna know if there is any method to take the iframe content from any domain just like every browser does. The fact is that when I try to get iframe content with file_get_contents in PHP it give

I have an iframe which content I need Google to index. Is this possible?

I have a classifieds website.

The iframe displays the results, and the php_page builds the results for the iframe. Basically the php_page builds a table containing the results from a mysql db, and outputs it.

My problem is that this doesn’t get indexed by google.

The reason I used an Iframe in the first place was to avoid page-reloading when hitting submit.

Ajax couldn’t be used due to various reasons I wont go into here.

I have a sitemap with URLS to all the classifieds also, but I don’t think this guarantees google to spider those URLS.

Trying to make the google spider crawl the results of a search form is not really the right approach.

Assuming you want google.com users to find your classifieds ads by searching google, the best approach is to create a set of static html pages from the ads, and link them (not invisibly) from elsewhere on your site (probably best from the home page — but such a link can be in a footer or something else unobtrusive)

They can also be linked to from your sitemap XML (you do have a sitemap XML file don’t you?)

Note: the doesn’t really come into this. Or Ajax.

There is no way to make any webspider fill out and submit forms.

Workaround: Every night, create a dump of the database and save the HTML to a file. Create a link from index.html to that file. Use CSS classes to make the link invisible. This way, Google will pick it up but users won’t see it.

Iframe — Will not setting location = ‘home.php’ on button, I am working on a site in which the user (after logging in) is sent to the home page of the site (home.php). On this home page are 4 separate iframes, each within a separate div and each populated

Help in iframe auto size

.Need help guys, I have created a php page named picture.php. In this page I am retrieving a certain image from the database where I used the following codes to display the retrieved image:

header("Content-Type: image/jpeg"); imagejpeg($img); imagedestroy($img); 

.next, I want to use this page to serve as the source for an image to be displayed in an iframe using the following code:

.various 3 is a jquery class where when i click the tag various 3 will pop-up an Iframe with picture.php inside it. and what i want to do is to set the size of the Iframe based on what is the size of the image from picture.php. help me with this please!

Here is tutorial for you to start from—> Here

You will have to store the resulting values within an array, or two separate variables.

In you iframe, this should work:

Javascript — Changing iFrame Content to PHP Content, I’m wondering how I can get my iFrames content (html) to update to code from a textarea and add php tags around it to make it actually appear. Code: $(«#iframehtml»).contents().find(«html»).html(Stack Overflow. About; Products For Teams; Stack Overflow Public questions & answers; Stack Overflow for Teams …

Dynamically resize iframe based on document size?

So what I’ve got is a page which will show a video with comments (similar to youtube). I dont want to reload the entire page when browsing through comments — and I really dont want to do the «show more» like we see on disquss. I want to break it into pages.

So I could do the video page with an iframe which contains the page of comments and users swap pages through the iframe. However, I’d prefer if the iframe didnt have its own scroll bar and it simply made the parent window change sizes.

I want people to be able to watch the video while browsing comments which is why i dont want the entire page to refresh when they go to a new comments page.

So is it possible to make an iframe which resizes itself based on the document size of the iframe?

Why not just use jQuery’s $.load() function to load comments into a div? Then you’ll have full control over the layout.

Javascript — How to use in-video ads?, I’m not sure how to use the in-video ads. I use JWplayer and . Here is what the Ad network provides. With the embed tag : wmode=»transparent» If you use JWPlayer (JS library or object HT Stack Overflow. About; Products For Teams; Stack Overflow Public questions & answers; Stack Overflow for Teams …

Источник

Full-screen iframe with a height of 100%

1. Change your DOCTYPE to something less strict. Don’t use XHTML; it’s silly. Just use the HTML 5 doctype and you’re good:

2. You might need to make sure (depends on the browser) that the iframe’s parent has a height. And its parent. And its parent. Etc:

I ran into the same problem, I was pulling an iframe into a div. Try this:

 

The height is set to 100vh which stands for viewport height. Also, the width could be set to 100vw, although you’ll likely run into problems if the source file is responsive (your frame will become very wide).

You could use frameset as the previous answer states but if you are insistent on using iFrames, the 2 following examples should work:

   
   

To hide scrolling with 2 alternatives as shown above:

   

Hack with the second example:

   

To hide the scroll-bars of the iFrame, the parent is made overflow: hidden to hide scrollbars and the iFrame is made to go upto 150% width and height which forces the scroll-bars outside the page and since the body doesn’t have scroll-bars one may not expect the iframe to be exceeding the bounds of the page. This hides the scrollbars of the iFrame with full width!

Источник

Оцените статью