Jump to content

Скрипт для плавной прокрутки страницы до якоря на той-же страницы


homm
 Share

Recommended Posts

AnchorScroller.js:

function anchorScroller(el, duration) {
if (this.criticalSection) {
return false;
}

if ((typeof el != 'object') || (typeof el.href != 'string'))
return true;

var address = el.href.split('#');
if (address.length < 2)
return true;

address = address[address.length-1];
el = 0;

for (var i=0; i<document.anchors.length; i++) {
if (document.anchors[i].name == address) {
el = document.anchors[i];
break;
}
}
if (el === 0)
return true;

this.stopX = 0;
this.stopY = 0;
do {
this.stopX += el.offsetLeft;
this.stopY += el.offsetTop;
} while (el = el.offsetParent);

this.startX = document.documentElement.scrollLeft || window.pageXOffset || document.body.scrollLeft;
this.startY = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;

this.stopX = this.stopX - this.startX;
this.stopY = this.stopY - this.startY;

if ( (this.stopX == 0) && (this.stopY == 0) )
return false;

this.criticalSection = true;
if (typeof duration == 'undefined')
this.duration = 500;
else
this.duration = duration;

var date = new Date();
this.start = date.getTime();
this.timer = setInterval(function () {
var date = new Date();
var X = (date.getTime() - this.start) / this.duration;
if (X > 1)
X = 1;
var Y = ((-Math.cos(X*Math.PI)/2) + 0.5);

cX = Math.round(this.startX + this.stopX*Y);
cY = Math.round(this.startY + this.stopY*Y);

document.documentElement.scrollLeft = cX;
document.documentElement.scrollTop = cY;
document.body.scrollLeft = cX;
document.body.scrollTop = cY;

if (X == 1) {
clearInterval(this.timer);
this.criticalSection = false;
}
}, 10);
return false;
}

test.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html dir="ltr">
<head>
<title>Форум htmlbook.ru / Результаты поиска</title>
<script type="text/javascript" src="AnchorScroller.js"></script>
<style type="text/css">
html, body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
font-family: 'Arial';
}

ul {
padding: 0;
margin: 0;
list-style: none;
}

.abs {
position: absolute;
}

#page-number-one,
#page-number-two,
#page-number-three,
#page-number-four,
#page-number-five {
width: 100%;
height: 100%;
top: 0;
}

#page-number-one {
left: 0;
background-color: #ccf;
}
#page-number-two {
left: 100%;
background-color: #fcc;
}
#page-number-three {
left: 200%;
background-color: #cfc;
}
#page-number-four {
left: 300%;
background-color: #ffc;
}
#page-number-five {
left: 400%;
background-color: #cff;
}

.padder {
padding: 20px;
}
.anchor {
display: block;
width: 100%;
height: 0;
line-height: 0;
top: 0; left: 0;
}

</style>
</head>
<body>
<div id="page-number-one" class="abs">
<a name="page1" class="anchor abs"></a>
<div class="padder">
<ul>
<li><a href="#page2" onclick="return anchorScroller(this)">Page2</a></li>
<li><a href="#page3" onclick="return anchorScroller(this)">Page3</a></li>
<li><a href="#page4" onclick="return anchorScroller(this)">Page4</a></li>
<li><a href="#page5" onclick="return anchorScroller(this)">Page5</a></li>
</ul>
</div>
</div>

<div id="page-number-two" class="abs">
<a name="page2" class="anchor abs"></a>
<div class="padder">
<ul>
<li><a href="#page1" onclick="return anchorScroller(this)">Page1</a></li>
<li><a href="#page3" onclick="return anchorScroller(this)">Page3</a></li>
<li><a href="#page4" onclick="return anchorScroller(this)">Page4</a></li>
<li><a href="#page5" onclick="return anchorScroller(this)">Page5</a></li>
</ul>
</div>
</div>

<div id="page-number-three" class="abs">
<a name="page3" class="anchor abs"></a>
<div class="padder">
<ul>
<li><a href="#page1" onclick="return anchorScroller(this)">Page1</a></li>
<li><a href="#page2" onclick="return anchorScroller(this)">Page2</a></li>
<li><a href="#page4" onclick="return anchorScroller(this)">Page4</a></li>
<li><a href="#page5" onclick="return anchorScroller(this)">Page5</a></li>
</ul>
</div>
</div>

<div id="page-number-four" class="abs">
<a name="page4" class="anchor abs"></a>
<div class="padder">
<ul>
<li><a href="#page1" onclick="return anchorScroller(this)">Page1</a></li>
<li><a href="#page2" onclick="return anchorScroller(this)">Page2</a></li>
<li><a href="#page3" onclick="return anchorScroller(this)">Page3</a></li>
<li><a href="#page5" onclick="return anchorScroller(this)">Page5</a></li>
</ul>
</div>
</div>

<div id="page-number-five" class="abs">
<a name="page5" class="anchor abs"></a>
<div class="padder">
<ul>
<li><a href="#page1" onclick="return anchorScroller(this)">Page1</a></li>
<li><a href="#page2" onclick="return anchorScroller(this)">Page2</a></li>
<li><a href="#page3" onclick="return anchorScroller(this)">Page3</a></li>
<li><a href="#page4" onclick="return anchorScroller(this)">Page4</a></li>
</ul>
</div>
</div>
</body>
</html>

Работает как минимум в пяти браузерах, не считая разных протестированных версий.

Основное преимущество ? легкость добавления к уже существующим якорям, сохранение работоспособности страницы с отключенной явой.

ЗЫ. Никто не знаает, document.anchors ? это вообще валидно?

Link to comment
Share on other sites

  • 1 year later...

Отлично! Но можно ли какнибудь ограничить скорость прокрутки страницы??? На длинных страницах прокрутка получается на слишком большой скорости - в результате всё движется рывками и сам эффект теряется. :)

Link to comment
Share on other sites

Изменение значения в

this.duration = 500;

с 500 на 5000 впринципе решает проблему, но замедляется вообще всё, тоесть на коротких дистанциях получается очень медленно)) А вот именно какойто ограничитель максимальных оборотов можно сварганить?

Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
 Share

  • Обсуждения

    • Актуальные контакты: Telegram: @Nikker_web E-Mail:   tarasevich.email@gmail.com Портфолио https://www.behance.net/d4d4186e Разрабатываю дизайн групп в соц сетях, сайтов, приложений, другой дизайн под заказ    
    • Актуальные контакты: Telegram: @Nikker_web E-Mail:   tarasevich.email@gmail.com   Разрабатываю дизайн групп в соц сетях, сайтов, приложений, другой дизайн под заказ   Портфолио https://www.behance.net/d4d4186e
    • Доброго всем времени суток. Прошу помощи. Научите принципу изменения футера. Движок Xenforo. Версия 2.2.10. Стиль дефолтный. Что именно нужно в итоге на фото примере. Мой шаблон app.footer less имеет следующее значение.  .p-footer { .xf-publicFooter(); a { .xf-publicFooterLink(); } } .p-footer-inner { .m-pageWidth(); .m-pageInset(); padding-top: @xf-paddingMedium; padding-bottom: @xf-paddingLarge; } .p-footer-row { .m-clearFix(); margin-bottom: -@xf-paddingLarge; } .p-footer-row-main { float: left; margin-bottom: @xf-paddingLarge; } .p-footer-row-opposite { float: right; margin-bottom: @xf-paddingLarge; } .p-footer-linkList { .m-listPlain(); .m-clearFix(); > li { float: left; margin-right: .5em; &:last-child { margin-right: 0; } a { padding: 2px 4px; border-radius: @xf-borderRadiusSmall; &:hover { text-decoration: none; background-color: fade(@xf-publicFooterLink--color, 10%); } } } } .p-footer-rssLink { > span { position: relative; top: -1px; display: inline-block; width: 1.44em; height: 1.44em; line-height: 1.44em; text-align: center; font-size: .8em; background-color: #4682B4; border-radius: 2px; } .fa-rss { color: white; } } .p-footer-copyright { margin-top: @xf-elementSpacer; text-align: center; font-size: @xf-fontSizeSmallest; } .p-footer-debug { margin-top: @xf-paddingLarge; text-align: right; font-size: @xf-fontSizeSmallest; .pairs > dt { color: inherit; } } @media (max-width: @xf-responsiveMedium) { .p-footer-row-main, .p-footer-row-opposite { float: none; } .p-footer-copyright { text-align: left; padding: 0 4px; // aligns with other links } }  
    • Нужны сайты с примерами верстки, типа https://css-tricks.com/. Типовые приемы и нестандартные на все случаи жизни. Накидайте ссылок.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue. See more about our Guidelines and Privacy Policy