Javascript-форум (https://javascript.ru/forum/)
-   Элементы интерфейса (https://javascript.ru/forum/dom-window/)
-   -   Плавающий блок, замирающий над футером (https://javascript.ru/forum/dom-window/43757-plavayushhijj-blok-zamirayushhijj-nad-futerom.html)

aklis 25.06.2016 01:02

дел

рони 16.02.2017 20:32

EvgenyTryap,
Пожалуйста, отформатируйте свой код!

Для этого его можно заключить в специальные теги: js/css/html и т.п., например:
[js]
... ваш код...
[/js]


О том, как вставить в сообщение исполняемый javascript и html-код, а также о дополнительных возможностях форматирования - читайте http://javascript.ru/formatting.

EvgenyTryap 16.02.2017 20:54

Возможно кто-нибудь сможет мне помочь!
Есть фиксированный блок(sidebar) к нижней границе. Мне нужно чтоб как только я прокручу до верхней границы футера(footer), фиксированный блок(sidebar) изменил стиль с position:fixed на position: absolute.

<html>
<head>
<style>
.wrapper{height:1500px;
position:relative;}
.footer{background:#F00;
height:300px;}
.sidebar{
height:50px;
position: fixed;
bottom:0;
left:0;
right:0;
background-color: #FF0000;}
</style>

</head>
<body>

<div class="wrapper">
<p>Your website content here.</p>
<div class="sidebar">fixed block</div>
</div>
<div class="footer">
<p>footer text</p>
</div>

</body>
</html>

рони 16.02.2017 21:01

футер сдвигающий блок
 
EvgenyTryap,
при условии DOCTYPE ...
<!DOCTYPE html>
<html>
 <head>
 <style>
 html *{
   margin:0;
   padding:0;
 }

 .wrapper{
   height:1500px;
   position:relative;
 }

 .footer{
   background:#F00;
   height:300px;
   border-top: rgb(255, 255, 0) 1px  dashed;
 }

 .sidebar{
   height:50px;
   position:fixed;
   bottom:0;
   left:0;
   right:0;
   background-color:#FF0000;
 }

 .sidebar.move{
   position:absolute;
 }

 </style>
   <script>
  window.addEventListener('DOMContentLoaded', function() {
      var footer = document.querySelector('.footer'),
          sidebar = document.querySelector('.sidebar'),
          top, height;
      document.addEventListener('scroll', function() {
          top = footer.getBoundingClientRect().top;
          height = document.documentElement.clientHeight;
          sidebar.classList[top < height ? "add" : "remove"]('move');
      });
  });
   </script>
 </head>
 <body>

 <div class="wrapper">
 <p>Your website content here.</p>
 <div class="sidebar">fixed block</div>
 </div>
 <div class="footer">
 <p>footer text</p>
 </div>

 </body>
 </html>

EvgenyTryap 16.02.2017 21:22

Огромное спасибо!!это то что нужно!!

EvgenyTryap 08.03.2017 18:33

А возможно ли как-нибудь реализовать тоже самое, но когда у html отключена прокрутка?

<!DOCTYPE html>
<html>
<head>

<style>
html {
position: relative;
height: 100%;
overflow: hidden;
}

body {
position: relative;
height: 100%;
overflow: auto;
}

 .wrapper{
   height:1500px;
   position:relative;
 }

 .footer{
   background:#F00;
   height:300px;
   border-top: rgb(255, 255, 0) 1px  dashed;
 }

 .sidebar{
   height:50px;
   position:fixed;
   bottom:0;
   left:0;
   right:0;
   background-color:#FF0000;
 }

 .sidebar.move{
   position:absolute;
 }

</style>
</head>

<body>

<div class="wrapper">
<p>Your website content here.</p>
<div class="sidebar">fixed block</div>
</div>

<div class="footer">
<p>footer text</p>
<div>

</body>
</html>

рони 08.03.2017 19:03

EvgenyTryap,
document.body.addEventListener('scroll'

EvgenyTryap 08.03.2017 19:15

Огромнейшее спасибо!!

JohnJohn 23.08.2017 17:20

Цитата:

Сообщение от рони (Сообщение 287830)
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>

Добрый день, все таки не могу разобраться в этом примере, как победить при уменьшении окна браузера проблему с поведением сайдбара, не понимаю, как сделать так, что бы при размерах видимой части поведение не менялось?

рони 23.08.2017 18:53

JohnJohn,
добавить красное
window.onload = window.resize = function () {

JohnJohn 23.08.2017 19:12

ничего не изменилось.

рони 23.08.2017 19:28

JohnJohn,
а так?
window.onscroll = window.resize =

JohnJohn 23.08.2017 19:31

пробовал, тоже нет(

рони 23.08.2017 19:35

JohnJohn,
можно только гадать в чём у вас проблема?

JohnJohn 23.08.2017 20:11

вот код.

<html>
  <head>
    <style>
    html, body {
      height: 100%;
    }
      .main {
        height: 100%;
      }
      .second_block {
        height: 100%;
      }
      #download_present_img{
        position: fixed;
    z-index: 9999;
    right: 15px;
    bottom: 20px;
    font-size: 50px;
    font-style: normal;
    margin-left: 20px;
    width: 40px;
    height: 40px;
    background: red;
}
.footer_block {
    display: flex;
    flex-flow: column nowrap;
    justify-content: center;
    align-items: center;
    position: relative;
    height: 190px;
    bottom: 0;
    left: 0;
}

.footer {
    color: #ffffff;
    display: flex;
    flex-flow: column nowrap;
    justify-content: center;
    align-items: center;
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 190px;
    background: #000;
}
    </style>
  </head>

  <body>
    <div class="main"></div>
    <div class='second_block'>
    <div id="download_present_img"></div>
    </div>
    <div id="footer_stop"  class="footer_block">
<div  class="footer">
<div class="text_footer">
  <p>footer</p>
</div>
    </div>
    </div>

    
<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.getElementById("download_present_img"),
         b = offset(a),
         f = window.getComputedStyle ? getComputedStyle(a, "") : a.currentStyle,
         d = a.offsetHeight + parseInt(f.marginTop) || 0,
         e = offset(document.getElementById("footer_stop"));
     window.onscroll = window.resize = 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>
 

  </body>
</html>

рони 23.08.2017 21:12

JohnJohn,

вариант...
<!DOCTYPE html>

<html>
  <head>
    <style>
    html, body {
      height: 100%;
    }
      .main {
        height: 100%;
      }
      .second_block {
        height: 100%;
      }
      #download_present_img{
        position: fixed;
    z-index: 9999;
    right: 15px;
    bottom: 20px;
    font-size: 50px;
    font-style: normal;
    margin-left: 20px;
    width: 40px;
    height: 40px;
    background: red;
}
.footer_block {
    display: flex;
    flex-flow: column nowrap;
    justify-content: center;
    align-items: center;
    position: relative;
    height: 190px;
    bottom: 0;
    left: 0;
}

.footer {
    color: #ffffff;
    display: flex;
    flex-flow: column nowrap;
    justify-content: center;
    align-items: center;
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 190px;
    background: #000;
}
    </style>
  </head>

  <body>
    <div class="main"></div>
    <div class='second_block'>
    <div id="download_present_img"></div>
    </div>
    <div id="footer_stop"  class="footer_block">
<div  class="footer">
<div class="text_footer">
  <p>footer</p>
</div>
    </div>
    </div>


<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.getElementById("download_present_img"),
         b = offset(a),
         f = window.getComputedStyle ? getComputedStyle(a, "") : a.currentStyle,
         d = a.offsetHeight + parseInt(f.marginTop) || 0,
         e = offset(document.getElementById("footer_stop"));
     window.onresize = function() {
    window.scrollTo(0,0);
    s = !0;
    a.style.position = "fixed";
    a.style.top = "";
    b = offset(a);
    e = offset(document.getElementById("footer_stop"));
};

     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>


  </body>
</html>

JohnJohn 23.08.2017 21:20

Хороший вариант... И как вам это в голову приходит!?! Спасибо.

EvgenyTryap 16.09.2018 15:55

Цитата:

Сообщение от рони (Сообщение 444491)
EvgenyTryap,
при условии DOCTYPE ...
<!DOCTYPE html>
<html>
 <head>
 <style>
 html *{
   margin:0;
   padding:0;
 }

 .wrapper{
   height:1500px;
   position:relative;
 }

 .footer{
   background:#F00;
   height:300px;
   border-top: rgb(255, 255, 0) 1px  dashed;
 }

 .sidebar{
   height:50px;
   position:fixed;
   bottom:0;
   left:0;
   right:0;
   background-color:#FF0000;
 }

 .sidebar.move{
   position:absolute;
 }

 </style>
   <script>
  window.addEventListener('DOMContentLoaded', function() {
      var footer = document.querySelector('.footer'),
          sidebar = document.querySelector('.sidebar'),
          top, height;
      document.addEventListener('scroll', function() {
          top = footer.getBoundingClientRect().top;
          height = document.documentElement.clientHeight;
          sidebar.classList[top < height ? "add" : "remove"]('move');
      });
  });
   </script>
 </head>
 <body>

 <div class="wrapper">
 <p>Your website content here.</p>
 <div class="sidebar">fixed block</div>
 </div>
 <div class="footer">
 <p>footer text</p>
 </div>

 </body>
 </html>

Цитата:

Сообщение от рони (Сообщение 446766)
EvgenyTryap,
document.body.addEventListener('scroll'

Подскажите, пожалуйста, а как это реализовать если прокрутка в блоке div (например с id="content") реализована?

рони 16.09.2018 16:44

EvgenyTryap,
сделайте минимальный макет, иначе можно только гадать.

j0hnik 16.09.2018 16:51

content.addEventListener('scroll'

рони 16.09.2018 16:57

j0hnik,
давай подождём макета :)

EvgenyTryap 16.09.2018 18:10

Цитата:

Сообщение от рони (Сообщение 494805)
EvgenyTryap,
сделайте минимальный макет, иначе можно только гадать.

<!DOCTYPE html>
<html>
 <head>
 <style>
 html *{
   margin:0;
   padding:0;
 }
.block{
height: 500px;
}

#content{
height: 1500px;
overflow-y: auto;
}

 .wrapper{
   height:1500px;
   position:relative;
 }

 .footer{
   background:#F00;
   height:300px;
   border-top: rgb(255, 255, 0) 1px  dashed;
 }

 .sidebar{
   height:50px;
   position:fixed;
   bottom:0;
   left:0;
   right:0;
   background-color:#FF0000;
 }

 .sidebar.move{
   position:absolute;
 }

 </style>
   <script>
  window.addEventListener('DOMContentLoaded', function() {
      var footer = document.querySelector('.footer'),
          sidebar = document.querySelector('.sidebar'),
          top, height;
      document.addEventListener('scroll', function() {
          top = footer.getBoundingClientRect().top;
          height = document.documentElement.clientHeight;
          sidebar.classList[top < height ? "add" : "remove"]('move');
      });
  });
   </script>
 </head>
 <body>

<div class="block">
<div id="content">
 <div class="wrapper">
 <p>Your website content here.</p>
 <div class="sidebar">fixed block</div>
 </div>
 <div class="footer">
 <p>footer text</p>
 </div>
</div>
</div>

 </body>
 </html>

Подскажите, пожалуйста, как это реализовать если прокрутка в блоке div (id="content") реализована?

рони 16.09.2018 19:09

EvgenyTryap,
не знаю, как это реализовать, плохо знаю css, чтоб сделать фиксированный блок в блоке.

рони 16.09.2018 19:51

EvgenyTryap,
ниже это не решение, это танцы с бубном ... макет того что требуется сделать, насколько я вас понял.
<!DOCTYPE html>
<html>
<head>
<style>
html *{
margin:0;
padding:0
}
.block{
    position: relative;
    overflow: hidden;
    height: 300px;
    width: 600px;
    margin: 30px auto
}

#content  {
height: 300px;
position: relative;
background-color: #D3D3D3;
overflow-y:  auto;
overflow-x: hidden;

}
.wrapper{
height: 1500px;
}

.footer{
background-color: #8B4513;
height:300px;
border-top: rgb(255, 255, 0) 1px  dashed;
}
.sidebar{
height:50px;
position: absolute;
top : 250px;
width: 100%;
background-color:#FF0000;
 z-index: 100;
}

</style>
<script>
window.addEventListener('DOMContentLoaded', function() {
var footer = document.querySelector('.footer'),
sidebar = document.querySelector('.sidebar'),
content = document.querySelector('#content'),
topFooter = footer.offsetTop, height = content.clientHeight,
heightsidebar = sidebar.clientHeight;
content.addEventListener('scroll', function() {
var scroll = content.scrollTop + height;
var topSidebar = "0";
var position = "relative";
if(topFooter > scroll ){
   topSidebar = (scroll - heightsidebar)+ "px";
   position = "absolute"
}
 sidebar.style.top = topSidebar;
 sidebar.style.position = position;
});
});
</script>
</head>
<body>
<div class="block">

<div id="content">

<div class="wrapper">
<p>Your website content here.</p>
</div>
<div class="sidebar">fixed block</div>
<div class="footer">
<p>footer text</p>
</div>
</div>

</div>
</body>
</html>

EvgenyTryap 16.09.2018 20:17

Да, именно это я и пытался сделать!)

Malleys 16.09.2018 21:53

рони, применил position: sticky; к вашему коду

<!DOCTYPE html>
<html>
	<head>
		<style>
html * {
	margin: 0;
	padding: 0;
}
.block {
	height: 300px;
	width: 600px;
	margin: 30px auto;
}

#content {
	height: 300px;
	overflow: auto;
	background-color: #D3D3D3;
}
.wrapper {
	height: 1500px;
}

footer {
	background-color: #8B4513;
	height: 300px;
	border-top: 1px dashed yellow;
}
.sidebar {
	height: 50px;
	position: -webkit-sticky; /* Safari */
	position: sticky;
	bottom: 0;
	background-color: red;
}

		</style>
	</head>
	<body>
		<div class="block">
			<div id="content">
				<div class="wrapper">
					<p>Your website content here.</p>
				</div>
				<div class="sidebar">fixed block</div>
				<footer>
					<p>footer text</p>
				</footer>
			</div>
		</div>
	</body>
</html>


Поддержка браузерами очень хорошая caniuse.com/#feat=css-sticky, в супер старых браузерах содержимое всё-равно остаётся доступным

UPD Если нужно, чтобы блок был именно так как с position: sticky? то можно примерно так эмулировать...
<!DOCTYPE html>
<html>
	<head>
		<style>
html * {
	margin: 0;
	padding: 0;
}
.block {
	height: 300px;
	width: 600px;
	margin: 30px auto;
}

#content {
	height: 300px;
	overflow: auto;
	background-color: #D3D3D3;
}
.wrapper {
	height: 250px;
	overflow: auto;
}

footer {
	background-color: #8B4513;
	height: 300px;
	border-top: 1px dashed yellow;
}
.sidebar {
	height: 50px;
	bottom: 0;
	background-color: red;
}
@supports(position: sticky) {
	.wrapper {
		height: auto;
	}

	.sidebar {
		position: sticky;
	}
}

		</style>
	</head>
	<body>
		<div class="block">
			<div id="content">
				<div class="wrapper">
					<p style="padding-bottom: 1500px;">
						Пусть содержимое длинное...
						Your website content here.
					</p>
				</div>
				<div class="sidebar">fixed block</div>
				<footer>
					<p>footer text</p>
				</footer>
			</div>
		</div>
	</body>
</html>

рони 16.09.2018 22:05

Malleys,
рассматривал этот вариант, в ie не работает, может есть правильная эмуляция (position: sticky;) или полифил какой для ie?

рони 17.09.2018 09:46

Цитата:

Сообщение от Malleys
UPD

ок, надо подумать, а реально сделать фиксированный блок в блоке, или position:fixed "выносит" фиксированный блок из блока и нет вариантов?

olifus 14.10.2018 12:49

Здравствуйте.
Как убрать дергание/мигание плавающего блока при прокрутке страницы?

$(window).scroll(function() {
		var sb_m = 50; /* отступ сверху и снизу */
		var mb = 200; /* высота подвала с запасом */
		var st = $(window).scrollTop();
		var sb = $(".sticky-block");
		if (sb.length === 0) return;
		var sbi = $(".sticky-block .inner");
		var sb_ot = sb.offset().top;
		var sbi_ot = sbi.offset().top;
		var sb_h = sb.height();

		if (sb_h + $(document).scrollTop() + sb_m + mb < $(document).height()) {
			if (st > sb_ot) {
				var h = Math.round(st - sb_ot) + sb_m;
				sb.css({
					"paddingTop": h
				});
			} else {
				sb.css({
					"paddingTop": 0
				});
			}
		}
	});

zulfukar 24.06.2020 23:53

Здравствуйте. Установил скрипт _http://sticky01.blogspot.com/2013/09/4.html и все работает. Единственное как только начинаешь прокрутку блока в код блока добавляется лишний div со стилями, которые портят вид блока. Помогите избавиться от них.
Вот код блока

<aside id="aside1">
	<span><h5>{blockname}</h5></span>
	<div>
		{blockcont} // это вывод данных блока (Лента новостей)
	</div>
</aside>
<div class="clear"></div>
<style>
.sticky {
  position: fixed;
  z-index: 101;
}
.stop {
  position: relative;
  z-index: 101;
}
</style>

<script>
(function(){
var a = document.querySelector('#aside1'), b = null, P = 0;  // если ноль заменить на число, то блок будет прилипать до того, как верхний край окна браузера дойдёт до верхнего края элемента. Может быть отрицательным числом
window.addEventListener('scroll', Ascroll, false);
document.body.addEventListener('scroll', Ascroll, false);
function Ascroll() {
  if (b == null) {
    var Sa = getComputedStyle(a, ''), s = '';
    for (var i = 0; i < Sa.length; i++) {
      if (Sa[i].indexOf('overflow') == 0 || Sa[i].indexOf('padding') == 0 || Sa[i].indexOf('border') == 0 || Sa[i].indexOf('outline') == 0 || Sa[i].indexOf('box-shadow') == 0 || Sa[i].indexOf('background') == 0) {
        s += Sa[i] + ': ' +Sa.getPropertyValue(Sa[i]) + '; '
      }
    }
    b = document.createElement('div');
    b.style.cssText = s + ' box-sizing: border-box; width: ' + a.offsetWidth + 'px;';
    a.insertBefore(b, a.firstChild);
    var l = a.childNodes.length;
    for (var i = 1; i < l; i++) {
      b.appendChild(a.childNodes[1]);
    }
    a.style.height = b.getBoundingClientRect().height + 'px';
    a.style.padding = '0';
    a.style.border = '0';
  }
  var Ra = a.getBoundingClientRect(),
      R = Math.round(Ra.top + b.getBoundingClientRect().height - document.querySelector('.blockRows').getBoundingClientRect().top + 30);  // селектор блока, при достижении верхнего края которого нужно открепить прилипающий элемент;  Math.round() только для IE; если ноль заменить на число, то блок будет прилипать до того, как нижний край элемента дойдёт до футера
  if ((Ra.top - P) <= 0) {
    if ((Ra.top - P) <= R) {
      b.className = 'stop';
      b.style.top = - R +'px';
    } else {
      b.className = 'sticky';
      b.style.top = P + 'px';
    }
  } else {
    b.className = '';
    b.style.top = '';
  }
  window.addEventListener('resize', function() {
    a.children[0].style.width = getComputedStyle(a, '').width
  }, false);
}
})()
</script>


С начала прокрутки в код после <aside id="aside1"> добавляется

<div style="background: rgba(0, 0, 0, 0) none repeat scroll 0% 0%; background-blend-mode: normal; border-block: 0px none rgb(51, 51, 51); border: 0px none rgb(51, 51, 51); border-radius: 0px; border-collapse: separate; border-end-end-radius: 0px; border-end-start-radius: 0px; border-inline: 0px none rgb(51, 51, 51); border-spacing: 0px; border-start-end-radius: 0px; border-start-start-radius: 0px; box-shadow: none; outline: rgb(51, 51, 51) none 0px; outline-offset: 0px; overflow-anchor: auto; overflow-block: visible; overflow-inline: visible; overflow-wrap: normal; overflow: visible; padding-block: 0px; padding: 0px; padding-inline: 0px; box-sizing: border-box; width: 320px;" class="">

сайт: _http://new.313news.net блок справа Лента новостей


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