Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Растягивание картинки (https://javascript.ru/forum/misc/5267-rastyagivanie-kartinki.html)

Amberwood 01.10.2009 13:36

Растягивание картинки
 
Добрый день!
Я написал скрипт, который растягивает картинку, придавая ей высоту и ширину документа.
<html>
<head>
<title>byLine</title>
<style type="text/css">html, body { width:100%; height:100%; padding:0;} p {line-height:1.8em; letter-spacing:0.1em; text-align:justify;} #content {position:absolute; padding:5px 300px 20px 200px; z-index:2;} body {margin:0; font-family:verdana, arial, sans-serif; font-size:76%;} #pic { z-index:1;  overflow: hidden; visibility:hidden;}</style>
</head>
<body>
<div id="content">
  <h1>ALICE'S ADVENTURES IN WONDERLAND</h1>
  <h3>Lewis Carroll</h3>
  <h2>THE MILLENNIUM FULCRUM EDITION 3.0</h2>
  <h3>CHAPTER I</h3>
  <h4>Down the Rabbit-Hole</h4>
    <p>Alice was beginning to get very tired of sitting by her sister
    on the bank, and of having nothing to do:  once or twice she had
    peeped into the book her sister was reading, but it had no
    pictures or conversations in it, 'and what is the use of a book,'
    thought Alice 'without pictures or conversation?'</p>
  <p>So she was considering in her own mind (as well as she could,
    for the hot day made her feel very sleepy and stupid), whether
    the pleasure of making a daisy-chain would be worth the trouble
    of getting up and picking the daisies, when suddenly a White
    Rabbit with pink eyes ran close by her.</p>
  <p>Alice was beginning to get very tired of sitting by her sister
    on the bank, and of having nothing to do:  once or twice she had
    peeped into the book her sister was reading, but it had no
    pictures or conversations in it, 'and what is the use of a book,'
    thought Alice 'without pictures or conversation?'</p>
  <p>So she was considering in her own mind (as well as she could,
    for the hot day made her feel very sleepy and stupid), whether
    the pleasure of making a daisy-chain would be worth the trouble
    of getting up and picking the daisies, when suddenly a White
    Rabbit with pink eyes ran close by her.</p>
  <p>Alice was beginning to get very tired of sitting by her sister
    on the bank, and of having nothing to do:  once or twice she had
    peeped into the book her sister was reading, but it had no
    pictures or conversations in it, 'and what is the use of a book,'
    thought Alice 'without pictures or conversation?'</p>
  <p>So she was considering in her own mind (as well as she could,
    for the hot day made her feel very sleepy and stupid), whether
    the pleasure of making a daisy-chain would be worth the trouble
    of getting up and picking the daisies, when suddenly a White
    Rabbit with pink eyes ran close by her.</p>

</div>
<script>
function getDocumentHeight()
{
   return (document.body.scrollHeight >
document.body.offsetHeight)?document.body.scrollHeight:document.body.offsetHeight;
}

function getDocumentWidth()
{
   return (document.body.scrollWidth >
document.body.offsetWidth)?document.body.scrollWidth:document.body.offsetWidth;
}
width = getDocumentWidth();
height = getDocumentHeight();
document.writeln('<img src="_images/b2.png" id="imgId" width="', width,'" height="', height,'"  class="fon">')
</script>
</body>

Тут всё хорошо работает. Но в данном файле скрипт находится внутри body. Мне же необходимо немного дополнить скрипт, чтобы он еще и на CSS влиял, а для этого нужно расположить скрипт в head. Вот что у меня получилось:
<html>
<head>
<title>byLine</title>
<style type="text/css">html, body { width:100%; height:100%; padding:0;} p {line-height:1.8em; letter-spacing:0.1em; text-align:justify;} #content {position:absolute; padding:5px 300px 20px 200px; z-index:2;} body {margin:0; font-family:verdana, arial, sans-serif; font-size:76%;} #pic { z-index:1;  overflow: hidden; visibility:hidden;}</style>
<script>
function getDocumentHeight()
{
   return (document.body.scrollHeight >
document.body.offsetHeight)?document.body.scrollHeight:document.body.offsetHeight;
}
function getDocumentWidth()
{
   return (document.body.scrollWidth >
document.body.offsetWidth)?document.body.scrollWidth:document.body.offsetWidth;
}
function init(){
var imgId= document.getElementById('imgId');
imgId.width = getDocumentWidth();
imgId.height = getDocumentHeight();
}
</script>
</head>
<body onLoad="init();">
<div id="content">
  <h1>ALICE'S ADVENTURES IN WONDERLAND</h1>
  <h3>Lewis Carroll</h3>
  <h2>THE MILLENNIUM FULCRUM EDITION 3.0</h2>
  <h3>CHAPTER I</h3>
  <h4>Down the Rabbit-Hole</h4>
    <p>Alice was beginning to get very tired of sitting by her sister
    on the bank, and of having nothing to do:  once or twice she had
    peeped into the book her sister was reading, but it had no
    pictures or conversations in it, 'and what is the use of a book,'
    thought Alice 'without pictures or conversation?'</p>
  <p>So she was considering in her own mind (as well as she could,
    for the hot day made her feel very sleepy and stupid), whether
    the pleasure of making a daisy-chain would be worth the trouble
    of getting up and picking the daisies, when suddenly a White
    Rabbit with pink eyes ran close by her.</p>
  <p>Alice was beginning to get very tired of sitting by her sister
    on the bank, and of having nothing to do:  once or twice she had
    peeped into the book her sister was reading, but it had no
    pictures or conversations in it, 'and what is the use of a book,'
    thought Alice 'without pictures or conversation?'</p>
  <p>So she was considering in her own mind (as well as she could,
    for the hot day made her feel very sleepy and stupid), whether
    the pleasure of making a daisy-chain would be worth the trouble
    of getting up and picking the daisies, when suddenly a White
    Rabbit with pink eyes ran close by her.</p>
  <p>Alice was beginning to get very tired of sitting by her sister
    on the bank, and of having nothing to do:  once or twice she had
    peeped into the book her sister was reading, but it had no
    pictures or conversations in it, 'and what is the use of a book,'
    thought Alice 'without pictures or conversation?'</p>
  <p>So she was considering in her own mind (as well as she could,
    for the hot day made her feel very sleepy and stupid), whether
    the pleasure of making a daisy-chain would be worth the trouble
    of getting up and picking the daisies, when suddenly a White
    Rabbit with pink eyes ran close by her.</p>
</div>
<img src="_images/b2.png" id="imgId" class="fon">
</body>
Но оказалось, что этот вариант не работает. Я что-то не так сделал, или этот скрипт невозможно расположить в head?

B~Vladi 01.10.2009 14:47

Всё должно работать.

Amberwood 01.10.2009 21:13

Цитата:

Сообщение от B~Vladi (Сообщение 31394)
Всё должно работать.

Но, к сожалению, не работает! Картинка имеет какие-то не понятные размеры, явно отличающиеся от размеров картинки в первом случае!

MininAS 02.10.2009 00:20

Нарисуй картинку отдельным скриптом в конце документа.

MininAS 02.10.2009 00:27

function getDocumentHeight()
{
   return (document.body.scrollHeight >
document.body.offsetHeight)?document.body.offsetHeight:document.body.scrollHeight;
}
function getDocumentWidth()
{
   return (document.body.scrollWidth >
document.body.offsetWidth)?document.body.offsetWidth:document.body.scrollWidth;
}


так нормально работает .

Amberwood 06.10.2009 22:04

Так всё хорошо, если нет прокрутки! А если есть прокрутка, то не подходит, т.к. картинка растягивается только по высоте окна, а не по высоте всего документа!

MininAS 06.10.2009 23:23

Ну если принципиально,! догоняй тогда в чем же дело, а так можно в принцепе и не обращать внимание на десяток откусанных пикселей с низу картинки, тем более если размер страницы будет больше видимой части экрана то РАЗНИЦЫ уже никакой нету (у картины в том и другом скрипте размер будет одинаков)!!!!!!!
Скорее всего браузеру принципиально каким образом ты выводишь объект (изображение): через скрипт в конце документа или же отдельным тегом.

MininAS 06.10.2009 23:34

Впечатление, что во вором варианте картинка рисуется с соблюдением пропорций т.е. высота не меньше чем ширина пропорционально.

Amberwood 07.10.2009 08:39

Ну у меня на некоторых страницах далеко не десяток откусанных пиксеклей.. В некоторых местах есть по 1000 пикселей на белом фоне...
Действительно браузеру по ходу не всё равно , где я вставляю скрипт...
Да я бы и оставил бы скрипт в конце документа, но дело в том что когда документ без прокрутки, т.е. высота документа меньше высоты окна, то тогда фон лучше вставлять через background. Вот я и хотел сделать скрипт, который определяет высоту документа, и в зависимости от этого вставлял фон через функцию или через background. А если скрипт в конце документа, то на background с его помощью не удаётся повлиять(((

B~Vladi 07.10.2009 10:36

Лучше засунуть весь контент в див и сравнивать его высоту с высотой документа.

ЗЫ:
function clientWidth(){return document.compatMode=='CSS1Compat'&&!window.opera?document.documentElement.clientWidth:document.body.clientWidth;}
function clientHeight(){return document.compatMode=='CSS1Compat'&&!window.opera?document.documentElement.clientHeight:document.body.clientHeight;}


Не забудь написать в стилях:
html, body{
  height:100%;
}

Amberwood 13.10.2009 11:19

Так?
<html>
<head>
<title>byLine</title>
<style type="text/css">html, body { width:100%; height:100%; padding:0;} p {line-height:1.8em; letter-spacing:0.1em; text-align:justify;} #content {position:absolute; padding:5px 300px 20px 200px; z-index:2;} body {margin:0; font-family:verdana, arial, sans-serif; font-size:76%; height:100%;} #pic { z-index:1;  overflow: hidden; visibility:hidden;}</style>
<script>

function clientWidth(){return document.compatMode=='CSS1Compat'&&!window.opera?document.documentElement.clientWidth:document.body.clientWidth;}
function clientHeight(){return document.compatMode=='CSS1Compat'&&!window.opera?document.documentElement.clientHeight:document.body.clientHeight;}
function init(){
var imgId= document.getElementById('imgId');
imgId.style.width = clientWidth();
imgId.style.height = clientHeight();
}
</script>
</head>

<body onLoad="init();">
<div id="content">
  <h1>ALICE'S ADVENTURES IN WONDERLAND</h1>
  <h3>Lewis Carroll</h3>
  <h2>THE MILLENNIUM FULCRUM EDITION 3.0</h2>
  <h3>CHAPTER I</h3>
  <h4>Down the Rabbit-Hole</h4>
    <p>Alice was beginning to get very tired of sitting by her sister
    on the bank, and of having nothing to do:  once or twice she had
    peeped into the book her sister was reading, but it had no
    pictures or conversations in it, 'and what is the use of a book,'
    thought Alice 'without pictures or conversation?'</p>
  <p>So she was considering in her own mind (as well as she could,
    for the hot day made her feel very sleepy and stupid), whether
    the pleasure of making a daisy-chain would be worth the trouble
    of getting up and picking the daisies, when suddenly a White
    Rabbit with pink eyes ran close by her.</p>
  <p>Alice was beginning to get very tired of sitting by her sister
    on the bank, and of having nothing to do:  once or twice she had
    peeped into the book her sister was reading, but it had no
    pictures or conversations in it, 'and what is the use of a book,'
    thought Alice 'without pictures or conversation?'</p>
  <p>So she was considering in her own mind (as well as she could,
    for the hot day made her feel very sleepy and stupid), whether
    the pleasure of making a daisy-chain would be worth the trouble
    of getting up and picking the daisies, when suddenly a White
    Rabbit with pink eyes ran close by her.</p>
  <p>Alice was beginning to get very tired of sitting by her sister
    on the bank, and of having nothing to do:  once or twice she had
    peeped into the book her sister was reading, but it had no
    pictures or conversations in it, 'and what is the use of a book,'
    thought Alice 'without pictures or conversation?'</p>
  <p>So she was considering in her own mind (as well as she could,
    for the hot day made her feel very sleepy and stupid), whether
    the pleasure of making a daisy-chain would be worth the trouble
    of getting up and picking the daisies, when suddenly a White
    Rabbit with pink eyes ran close by her.</p>
 </div>

<img src="_images/b2.png" id="imgId" class="fon">

</body>

Не работает. Фон растягивается по высоте окна. Ниже текст идёт уже на белом фоне. В IE ваще хрень какая-то... Или я неправильно понял Вас?!

А может быть можно как-нибудь повлиять на CSS или background скриптом, находящемся в body, а не в head? Ведь та часть скрипта, которая отвечает за растяжение картинки при расположении в body работает. Тогда бы проблема была решена!

x-yuri 20.10.2009 03:03

а зачем эти извращения с растягиванием картинки и #content { position: absolute }. Есть причины не ставить картинку в фон к body?

Amberwood 20.10.2009 21:36

Цитата:

Сообщение от x-yuri (Сообщение 32891)
а зачем эти извращения с растягиванием картинки и #content { position: absolute }. Есть причины не ставить картинку в фон к body?

Проблема состоит в том, что скрипт растягивает картинку именно по ширине и высоте окна, а окно может быть раскрыто не на весь экран. И если это так, то если пользователь растянет окно на больший размер, то окажется, что фон по прежнему имеет старые размеры, то есть предыдущие размеры окна.
Для решения этой проблемы я решил задать условие, которое определяет размеры текста относительно размеров экрана, чтобы определить, будет ли прокрутка. Если прокрутка будет - то со скриптом проблем нет. Если прокрутки нет, то проще вставить фон через background.
И вот получается, что по идее, чтобы скрипт влиял на background, он должен находиться в head, а растягивание фона работает только в body.
Поэтому нужно добиться либо чтобы обе части скрипта работали в одном месте, либо, если это возможно, как-то разбить скрипт на 2 части, и чтобы часть находящаяся в body в случае необходимости вызывала часть, находящуюся в head. Или еще что-то...

x-yuri 21.10.2009 03:12

Цитата:

Сообщение от Amberwood
И если это так, то если пользователь растянет окно на больший размер, то окажется, что фон по прежнему имеет старые размеры, то есть предыдущие размеры окна.

т.е. картинка будет непропорционально масштабироваться? И какие у нее изначальные размеры?

B~Vladi 21.10.2009 10:46

Сам себе создал проблему. Нельзя ли по-проще быть?!

Amberwood 21.10.2009 15:11

Цитата:

Сообщение от x-yuri (Сообщение 33006)
т.е. картинка будет непропорционально масштабироваться? И какие у нее изначальные размеры?

Да, непропорционально. Но она имеет радужный переливающийся цвет. И как бы она не растягивалась, смотрится прекрасно.
Цитата:

Сообщение от B~Vladi (Сообщение 33032)
Сам себе создал проблему. Нельзя ли по-проще быть?!

Ну пока обхожусь без этого фона. Но очень бы хотелось его использовать. Проблема состоит в том, что язык HTML умеет растягивать в ширину, но не умеет в высоту. А повторение фона тут не прокатит(( Так что простых вариантов решения пока не вижу...

B~Vladi 21.10.2009 15:16

Цитата:

Сообщение от Amberwood
HTML умеет растягивать в ширину, но не умеет в высоту

Он умеет растягивать высоту (height:100%; ), но это без учёта скрола. В принципе, твою проблему можно решить и на голом HTML, но такой трюк подходит не для всех шаблонов;)

x-yuri 21.10.2009 15:32

Цитата:

Сообщение от Amberwood
Но она имеет радужный переливающийся цвет.

а можно... заценить?

Amberwood 21.10.2009 21:35

Цитата:

Сообщение от B~Vladi (Сообщение 33081)
Он умеет растягивать высоту (height:100%; ), но это без учёта скрола. В принципе, твою проблему можно решить и на голом HTML, но такой трюк подходит не для всех шаблонов;)

height:100%; как раз
только при скроллинге и растянет. Если скроллинга не будет, то можно сделать либо чтобы картинке придавался истиный размер, либо, чтобы растягивало только на высоту текста!
Цитата:

Сообщение от x-yuri (Сообщение 33088)
а можно... заценить?

Можно:

B~Vladi 22.10.2009 10:07

Цитата:

Сообщение от Amberwood
только при скроллинге и растянет. Если скроллинга не будет, то можно сделать либо чтобы картинке придавался истиный размер, либо, чтобы растягивало только на высоту текста!

Если нет скроллинга - пишем в CSS:
html,body{
width:100%;
height:100%;
}

Тогда будет растягивать:)

Amberwood 22.10.2009 14:41

По крайней мере в данном случае это не спасает((


Часовой пояс GMT +3, время: 03:10.