Плавающий блок, замирающий над футером
Привет! Помогите разобраться. :)
Необходимо подключить скрипт для правого сайдбара как тут: http://sticky01.blogspot.ru/2013/09/4.html. вот мой сss: Код:
<script> function offsetPosition(e) { var offsetTop = 0; do {offsetTop += e.offsetTop;} while (e = e.offsetParent); return offsetTop; } var aside = document.querySelector('aside'), OP = offsetPosition(aside); window.onscroll = function() { // window.pageYOffset - прокрутка; // document.documentElement.scrollHeight - высота всего документа; // aside.offsetHeight - высота элемента if (window.pageYOffset > document.documentElement.scrollHeight - 9720 - aside.offsetHeight) { aside.className = 'button_bottom'; aside.style.top = (document.documentElement.scrollHeight - 1230 - aside.offsetHeight - OP) + 'px'; } else { aside.style.top = '0'; aside.className = (OP < window.pageYOffset ? 'sidebar' : ''); } } </script> В html блок div class="sidebar" c контентом (текст и картинки) Скопированный скрипт не работает. что необходимо изменить? |
а что необходимо изменить в коде?
|
тогда почему у меня не работает?
|
мне надо надо ПОДКЛЮЧИТЬ скрипт К МОЕМУ КОДУ. а сам по-себе он работает, тут и не поспоришь)
|
есть еще (другие) знатоки? :)
|
:write: вариант фиксации блока перед футером ...
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>demo</title> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <style type='text/css'> body{padding:0px;margin:0px} *{margin:0} html,body{height:1000px} .wrapper{min-height:100%;height: auto !important;height:100%;margin:0 auto -170px} .footer,.push{height:270px} .footer{background:#F00} .sidebar{ width:245px; margin-top:15px; margin-left:300px; height:500px; padding:13px; font-size:14px; font-style: italic; font-family: 'Arial'; border: 2px solid #bab89a; position: fixed; background-color: #FF0000; } .sidebar .content .text{ position: absolute; } </style> <script type='text/javascript'> $(function () { var a = $(".sidebar"), c = a.offset(), d = a.outerHeight(!0), e = $(".footer").offset(); $(document).scroll(function () { var b = $(this).scrollTop(), b = e.top - (b + d + c.top); 0 < b ? a.css({ background: "red", top: c.top }) : a.css({ background: "green", top: c.top + b }) }) }); </script> </head> <body> <div class="sidebar"></div> <div class="wrapper"> <p>Your website content here.</p> <div class="push"></div> </div> <div class="footer"> <p>Copyright (c) 2013</p> </div> </body> </html> |
рони, спасибо за ваш код) а с моим вариантом кода, можно что-то сделать? и без jquery
|
Navaho,
сделайте макет страницы в песочнице http://learn.javascript.ru/play или тут, так быстрее кто-то откликнется, сейчас можно только гадать по вашим фрагментам что и почему у вас неработает |
Navaho,
Вариант фиксации блока без jquery на фреймворке Vanilla JS ... :dance: <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>demo</title> <style type='text/css'> body{padding:0px;margin:0px} *{margin:0} html,body{height:1000px} .wrapper{min-height:100%;height: auto !important;height:100%;margin:0 auto -170px} .footer,.push{height:270px} .footer{background:#F00} .sidebar{ width:245px; margin-top:15px; margin-left:700px; height:500px; padding:13px; font-size:14px; font-style: italic; font-family: 'Arial'; border: 2px solid #bab89a; position: fixed; background-color: #FF0000; } .sidebar .content .text{ position: absolute; } </style> <script> function offset(a) { for (var b = 0; a;) b += parseInt(a.offsetTop), a = a.offsetParent; return b } window.onload = function () { var a = document.querySelector(".sidebar"), b = offset(a), d = a.offsetHeight + 15, // margin-top e = offset(document.querySelector(".footer")); window.onscroll = function () { var c = window.pageYOffset || document.documentElement.scrollTop, c = e - (c + d + b); 0 < c ? a.style.top = b + "px" : a.style.top = b + c + "px" } }; </script> </head> <body> <div class="sidebar"></div> <div class="wrapper"> <p>Your website content here.</p> <div class="push"></div> </div> <div class="footer"> <p>Copyright (c) 2013</p> </div> </body> </html> |
Navaho,
и наконец фиксация блока на чистом js улучшенный вариант ... :write: изменение стилей блока происходит только в момент соединения/разьединения блока с футером <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>demo</title> <style type='text/css'> body{padding:0px;margin:0px} *{margin:0} html,body{height:1000px} .wrapper{min-height:100%;height: auto !important;height:100%;margin:0 auto -170px} .footer,.push{height:270px} .footer{background:#F00} .sidebar{ width:245px; margin-top:15px; margin-left:400px; height:500px; padding:13px; font-size:14px; font-style: italic; font-family: 'Arial'; border: 2px solid #bab89a; position: fixed; background-color: #00FF7F; } .sidebar .content .text{ position: absolute; } </style> <script> function offset(a) { for (var b = 0; a;) b += parseInt(a.offsetTop), a = a.offsetParent; return b } var s = !0; window.onload = function () { var a = document.querySelector(".sidebar"), b = offset(a), f = window.getComputedStyle ? getComputedStyle(a, "") : a.currentStyle, d = a.offsetHeight + parseInt(f.marginTop) || 0, e = offset(document.querySelector(".footer")); window.onscroll = function () { var c = window.pageYOffset || document.documentElement.scrollTop, c = e - (c + d + b); s != 0 < c && ((s = 0 < c) ? (a.style.top = b + "px", a.style.position = "fixed") : (a.style.top = e - d + "px", a.style.position = "absolute")) } }; </script> </head> <body> <div class="sidebar"></div> <div class="wrapper"> <p>Your website content here.</p> <div class="push"></div> </div> <div class="footer"> <p>Copyright (c) 2013</p> </div> </body> </html> |
Navaho,
скиньте вашу веб страницу с css в .zip файл и загрузите в файлообменник, я напишу вам код |
рони, спасибо! сейчас буду пробовать
|
js-js, "в файлообменник" это куда? а можно по электронке?
|
рони,
нет, не получается, сайдбар только съехал немного вниз... скрипты не поддаются моему понимаю))) |
Navaho,
сделайте макет страницы хотябы с css |
рони,
моя страница подобна этой: http://all-blogers.com/yanal_coffee-imbir/ и сайбар такой же. Только у меня еще есть расстояние для хэдера, т.е. сайдбар расположен вверху с отступом. Таком образом, надо предусмотреть момент, чтобы сайдбар при прокрутке приклеивался к верху окна браузера. И еще необходима внутренняя прокрутка сайдбара без появления скролла... |
Цитата:
|
рони - а как реализовать что бы sidebar сразу цеплялся к футеру или к нижнему краю окна, если футер ушел ниже окна?
|
Roman S,
задайте bottom: 0px; для .sidebar |
Если не менять размер окна, нормально работает. Но если изменить, он сразу сыпится и не понимает где низ футера или окна.
|
Цитата:
|
Слишком мелкий для метода job.
Здесь скорее вопрос вполучении координатов границы div в катором находится sidebar и нижней границы окна. |
Roman S,
молодец придумай код |
координаты обьекта у нас есть, вопрос как узнать координаты нижней границы окна?
|
Цитата:
|
|
Вот этот вариант, то что нужно!
|
Остановка блока при скроллинге
У меня стоит скрипт плавающего блока, где то в инете скачал.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script> <script type="text/javascript"> $(function() { var offset = $("#fixed").offset(); var topPadding = 20; $(window).scroll(function() { if ($(window).scrollTop() > offset.top) { $("#fixed").stop().animate({marginTop: $(window).scrollTop() - offset.top + topPadding}); } else {$("#fixed").stop().animate({marginTop: 0});};}); }); </script> Ребят, подскажите как остановить блок при прокрутке вниз. Сейчас скролит до бесконечности и футер невозможно увидеть. Сайт http://allremont59.ru |
sergiocharm,
$(function() { var offset = $("#fixed").offset(); var topPadding = 20, bottomPadding = 210; //высота над которой остоновится $(window).scroll(function() { if ($(window).scrollTop() > offset.top) { if ($(document).height() - bottomPadding > $(window).scrollTop() + $("#fixed").height()) $("#fixed").stop().animate({ marginTop: $(window).scrollTop() - offset.top + topPadding }); } else { $("#fixed").stop().animate({ marginTop: 0 }); }; }); }); |
Помогите мне прижать так же как в Ваших примерах. Не получается что то. Пожалуйста
|
anmast,
:blink: |
рони,
при заужении браузера блок не останавливается и лезет до бесконечности. как в этом случае поступить? |
sergiocharm,
:) ещё вариант $(function() { var elem = $("#fixed"), h = elem.offset().top ; $(window).scroll(function(){ var top = $(this).scrollTop(); elem.css( {'top': top> h ? 20 : '', 'position': top > h ? 'fixed' : ''})}) }); |
Спасибо! Поступил проще, убрал при маленьком разрешении
|
Вот пример, как сделать плавающий блок ;)
|
Цитата:
:-? |
Jeff,
и не очень хорошая реализация. Если после загрузки страницы изменится смещение до "плавающего" блока (подгрузится что-то выше него, отобразится картинка, изменится ориентация экрана...) блок будет фиксироваться в неправильном положении скролла. |
Цитата:
|
sergiocharm,
попробуйте так $(function() { var offset = $("#fixed").offset(); var topPadding = 20, bottomPadding = 210; $(window).scroll(function() { var max = $(document).height() - ($(window).height() - bottomPadding), scroll = $(window).scrollTop(); if (scroll > offset.top && scroll < max) { if ($(document).height() - bottomPadding > scroll + $("#fixed").height()) $("#fixed").stop().animate({ marginTop: scroll - offset.top + topPadding }) } else $("#fixed").stop().animate({ marginTop: 0 }) }) }); |
|
Часовой пояс GMT +3, время: 09:57. |