Как заставить плавающий нижний колонтитул прилипать к нижней части области просмотра в IE 6?

Я знаю, что с position: fixed это будет легко, но, к сожалению, я застрял в поддержке IE 6. Как я могу это сделать? Я бы предпочел использовать CSS, чтобы быть чистым, но если мне придется использовать Javascript, это еще не конец света. В моей текущей реализации у меня есть «плавающий нижний колонтитул», который плавает над основной областью содержимого и позиционируется с помощью Javascript. Реализация, которая у меня сейчас есть, не особенно элегантна даже с Javascript, поэтому мои вопросы:

  1. Есть ли способ сделать это без Javascript?
  2. Если мне нужно использовать Javascript, есть ли какие-нибудь «приятные» решения этой проблемы с плавающим нижним колонтитулом? Под "хорошим" я подразумеваю то, что будет работать во всех браузерах, не перегружает ресурсы браузера (так как его придется часто пересчитывать) и является элегантным / простым в использовании (т.е. было бы неплохо написать что-то вроде new FloatingFooter("floatingDiv")).

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

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

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

skaffman 29.09.2008 00:31

Почему только тег Javascript? Для меня это вопрос CSS.

Toon Krijthe 29.09.2008 00:40

Мне интересно, сколько людей все еще используют IE6?

mr-euro 25.05.2009 01:58
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
12
3
32 278
6
Перейти к ответу Данный вопрос помечен как решенный

Ответы 6

Я делал это с помощью выражений CSS в прошлом.

Попробуйте что-то вроде этого:

.footer {
    position: absolute;
    top: expression((document.body.clientHeight - myFooterheight) + "px");
}

подробнее здесь
и тут

Поэтому используйте выражение () для IE6 и position: fixed для всех остальных, используя условные комментарии.

Eevee 29.09.2008 02:39

да, это звучит как совершенно правильный способ решить проблему Только IE.

nickf 29.09.2008 05:57

Если нижний колонтитул имеет фиксированную высоту, и вы знаете это и можете жестко запрограммировать его в CSS, вы можете сделать это следующим образом:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <style>
        .content
        {
            position : absolute;
            top : 0;
            left : 0;
            right : 0;
            bottom : 50px; /* that's the height of the footer */
            overflow : auto;
            background-color : blue;
        }
        .footer
        {
            position : absolute;
            left : 0;
            right : 0;
            bottom : 0px; /* that's the height of the footer */
    height : 50px;
            overflow : hidden;
            background-color : green;
        }
        </style>
    </head>
    <body>
        <div class = "content">
             everything from the page goes here
             everything from the page goes here
             everything from the page goes here
             everything from the page goes here
             everything from the page goes here
             everything from the page goes here
             everything from the page goes here
             everything from the page goes here
             everything from the page goes here
             everything from the page goes here
             everything from the page goes here
             everything from the page goes here
             everything from the page goes here
             everything from the page goes here
             everything from the page goes here
        </div>
        <div class = "footer">
             the footer
        </div>
    </body>
</html>
Ответ принят как подходящий

Это может сработать для вас. У меня он работает в IE6 и Firefox 2.0.0.17. Дать ему шанс. Я сделал нижний колонтитул очень высоким, просто для эффекта. Очевидно, вы бы изменили его на то, что вам нужно. Надеюсь, это сработает для вас.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Liquid Footer</title>
    <style type = "text/css">
    .footer {
background-color: #cdcdcd;
height: 180px;
text-align: center;
font-size:10px;
color:#CC0000;
font-family:Verdana;
padding-top: 10px;
width: 100%;
position:fixed;
left: 0px;
bottom: 0px;
}
    </style>
    <!--[if lte IE 6]>
    <style type = "text/css">
    body {height:100%; overflow-y:auto;}
    html {overflow-x:auto; overflow-y:hidden;}
    * html .footer {position:absolute;}
    </style>
    <![endif]-->
</head>

<body>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   This is to expand the content on the page<br>
   <div class = "footer">-- This is your liquid footer --</div>
</body>
</html>

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

Keith Bentrup 25.05.2009 02:04

я всегда забываю о позиции: фиксированная; ДА УЖ!

jwl 06.10.2011 22:02

Если вы поместите height в 100% и overflow: auto в теги <html/> и <body/>, все, что имеет абсолютное положение, станет фиксированным. Это самый простой вариант, потому что он довольно забавный, со странно расположенными полосами прокрутки, но его можно настроить для получения достойных результатов. пример

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
        <style>
            html, body
            {
                height: 100%;
                overflow: auto;
            }

            .fixed
            {
                position: absolute;
                bottom: 0px;
                height: 40px;
                background: blue;
                width: 100%;
            }
        </style>
    </head>
    <body>
        <div class = "fixed"></div>
        overflow....<br />
        overflow....<br />
        overflow....<br />
        overflow....<br />
        overflow....<br />
        overflow....<br />
        overflow....<br />
        overflow....<br />
        overflow....<br /><!-- ... -->
    </body>
</html>

если вы не хотите использовать условные комментарии, чтобы вы могли поместить CSS в отдельный файл, используйте !important. Что-то вроде этого:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
               "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html>
    <head>
        <style>
            html {
                overflow-x: auto;
                overflow-y: scroll !important;
                overflow-y: hidden; /* ie6 value b/c !important ignored */
            }

            body {
                padding:0;
                margin:0;
                height: 100%;
                overflow-y: hidden !important;
                overflow-y: scroll; /* ie6 value b/c !important ignored */
            }

            #bottom {
                background-color:#ddd;
                position: fixed !important;
                position: absolute; /* ie6 value b/c !important ignored */
                width: 100%;
                bottom: 0px;
                z-index: 5;
                height:100px;
            }
            #content {
                font-size: 50px;
            }
        </style>
    </head> 
    <body>
        <div id = "bottom">
            keep this text in the viewport at all times
        </div>
        <div id = "content">
            Let's create enough content to force scroll bar to appear.
            Then we can ensure this works when content overflows.
            One quick way to do this is to give this text a large font
            and throw on some extra line breaks.
            <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
            <br/><br/><br/><br/><br/><br/><br/><br/>    
        </div>  
    </body> 
</html>

$(function(){
    positionFooter(); 
    function positionFooter(){
        if ($(document).height() < $(window).height()){//Without the body height conditional the footer will always stick to the bottom of the window, regardless of the body height, $(document).height() - could be main container/wrapper like $("#main").height() it depend on your code
            $("#footer").css({position: "absolute",top:($(window).scrollTop()+$(window).height()-$("#footer").height())+"px"})
        }   
    }

    $(window).scroll(positionFooter);
    $(window).resize(positionFooter);
});

Другие вопросы по теме