document.observe('dom:loaded', fun-6ren">
gpt4 book ai didi

javascript - 当主导航离开 View 时为粘性导航应用样式

转载 作者:太空宇宙 更新时间:2023-11-04 10:15:51 25 4
gpt4 key购买 nike

我用这段代码让我的移动导航变得粘滞:

<div class="stickyTest" id="stickyTest2">
<ul id="nav">
<li class="homeicon"><a href="<?php echo $this->getUrl('')?>" class=""></a></li>
<?php echo $_menu ?>

</ul>

<script type="text/javascript">
document.observe('dom:loaded', function() {
new MobileNavigation();

var searchToggle = $('mobile-search-toggle'),
searchForm = $('search_mini_form');
if (searchToggle && searchForm) {
searchToggle.observe('click', function() {
searchForm.toggleClassName('shown');
});
}
});
</script>

<script type="text/javascript">
function ajaxsearchsubmit(form){
var search = encodeURIComponent(form.w.value);
document.activeElement.blur();
window.location="http://www.test.co.uk/search/go?w="+search;
return false;
}
</script>
<div class="clear"></div>
</div>

还有CSS:

.stickyTest {
background: #362011;
position:fixed;
z-index:1000;
width:100%;
top:0px;
}
#stickyTest2 {margin-top:40px;}

现在我的问题是我只需要 .stickyTest 类的 position:fixedmargin-top:40px #stickyTest2 当用户向下滚动并且顶部导航离开 View 时要应用的 id。那么两个问题:

  1. 如何在滚动条上应用这些特定样式?
  2. 有没有办法检测顶部导航何时超出视野?我知道我可以做一些事情,例如当用户滚动超过 200 像素但屏幕尺寸不同等时应用粘性导航样式。我想知道是否有更灵活的方法?

最佳答案

How do I apply those specific styles on scroll?

如果 您可以使用 jQuery 库,您可以使用以下代码检测滚动事件:

$(window).scroll(function(){
// your code
});

然后你可以使用 addClass()removeClass() 来玩类。

Is there a way to detect when the top navigation goes out of view?

您可以使用这段代码获取导航栏的高度,再次使用 jQuery 并使用 scrollTop() 在您的 scroll() 函数中进行测试方法,像这样代替:

var stickyHeight = $('.stickyTest').height(); 
$(window).scroll(function(){
// if your top navbar is out of view
if($(window).scrollTop() > stickyHeight){
$('.stickyTest').addClass('fixed');
}else{
$('.stickyTest').removeClass('fixed');
}
});

See a live example

来源:

滚动():https://api.jquery.com/scroll/

添加类():https://api.jquery.com/addclass/

removeClass():https://api.jquery.com/removeclass/

scrollTop():https://api.jquery.com/scrollTop/

关于javascript - 当主导航离开 View 时为粘性导航应用样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37252759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com