【问题标题】:Jquery script stops nav from workingJquery 脚本停止 nav 工作
【发布时间】:2012-12-14 03:39:00
【问题描述】:

在我的一页Website 上,我添加了一个脚本以在不同的 div 框之间进行平滑移动。但突然导航停止工作。这是最后一个打破它的。

<script>
$(function(){
var sections = {},
    _height  = $(window).height(),
    i        = 0;

// Grab positions of our sections 
$('.section').each(function(){
    sections[this.name] = $(this).offset().top;
});

$(document).scroll(function(){
    var pos = $(this).scrollTop();

    // Look in the sections object and see if any section is viewable on the screen. 
    // If two are viewable, the lower one will be the active one. 
    for(i in sections){
        if(sections[i] > pos && sections[i] < pos + _height){
            $('a').removeClass('active');
            $('#nav_' + i).addClass('active');
            }  
        }
    });
});




        $(".scroll").click(function(event){
            event.preventDefault();
            var full_url = this.href;
            var parts = full_url.split("#");
            var trgt = parts[1];
            var target_offset = $("#"+trgt).offset();
            var target_top = target_offset.top;
            $('html, body').animate({scrollTop:target_top}, 500);
        }); 

</script>  

【问题讨论】:

  • Object has no method localScroll,你在哪里定义了localScroll()
  • 阅读我投反对票的答案,我所做的更新应该可以解决问题。从&lt;nav&gt; 更改为&lt;div&gt;

标签: jquery navigation nav


【解决方案1】:

控制台在line 14上显示错误

$('#nav').localScroll();

还有Cannot read property 'top' of undefined错误

更新

看起来没有 id 为 section1

的元素

应该是nav_section1

这一行

$("#"+trgt).offset();

应该是

$("#nav_"+trgt).offset();  OR  $('[href="#' + trgt + "]').offset()

当您获得offset() 值时,还要确保元素未隐藏..

【讨论】:

  • OR 后的最后一位出现语法错误。当我尝试删除该部分时,语法错误消失了。我也可以再次使用导航,但它没有转到不同的 div,它只是向下滚动了大约 500 像素。
  • 你能不能创建一个复制 isuue 的小提琴以便它可以工作
【解决方案2】:

一定会喜欢 Chrome 的 Inspector...您错过了一个分号。

<script type="text/javascript">
$(function(){
    $('#nav').localScroll();
});
</script>

你为什么使用&lt;nav&gt;?说明中谈到了使用&lt;div&gt;


试试这个:

<div id="nav">
    <ul>
        <li><a id="nav_section1" href="#section1" class="scroll active">Section 1</a></li>
        <li><a id="nav_section2" href="#section2" class="scroll">&gt;Section 2</a></li>
        <li><a id="nav_section3" href="#section3" class="scroll">&gt;Section 3</a></li>
        <li><a id="nav_section4" href="#section4" class="scroll">&gt;Section 4</a></li>
        <li><a id="nav_section5" href="#section5" class="scroll">&gt;Section 5</a></li>
        <li><a id="nav_section6" href="#section6" class="scroll">&gt;Section 6</a></li>
        <li><a id="nav_section7" href="#section7" class="scroll">&gt;Section 7</a></li>
     </ul>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-26
    • 1970-01-01
    • 2015-12-03
    • 2014-12-16
    • 2023-03-20
    • 2017-01-10
    • 1970-01-01
    • 2010-12-17
    相关资源
    最近更新 更多