0

我做了一些 Jquery,你可以在下面看到这个小提琴:http: //madaxedesign.co.uk/dev/Test/ http://jsfiddle.net/x82mU/1/

代码:

$(document).ready(function() {
var $root = $('html, body ');
$('.scroll a').click(function(e) {
    var href = $.attr(this, 'href');
    $root.animate({
        scrollTop: $(href).offset().top
    }, 500, function () {
        window.location.hash = href;
    });
    return false;
});

// Responsive menu 
$(function() {
    var pull        = $('#pull'),
        menu        = $('nav ul'),
        menuHeight  = menu.height()

    $(pull).on('click', function(e) {
        e.preventDefault();
        menu.slideToggle();
    });

    $(window).resize(function(){
        var w = $(window).width();
        if(w > 320 && menu.is(':hidden')) {
            menu.removeAttr('style');
        }
    });
}); 
 });

但它解决了这个错误:Uncaught TypeError: Cannot read property 'top' of undefined

这阻止了我的下一个 Jquery 工作。

我想知道是否有人可以让我知道为什么,或者给我一个解决方案?

非常感谢

4

2 回答 2

2

您正在尝试获取href许多菜单项中不存在的选择器。

IE:

    <li><a href="#">Home</a></li>
    <li><a href="#aboutUs">About us</a></li>
    <li><a href="#">Portfolio</a></li>        
    <li><a href="#">Contact us</a></li>

$(href).offset().top //here offset() of an empty jquery object is undefined.

不是问题,但你可以这样this.href$.attr(this, 'href')

试试这个:

 $('.scroll a').click(function(e) {
    var href = $(this).attr("href"), $el = $(href), top=0; //default top to 0
       if($el.length)  //if there is element matching the href
          top = $el.offset().top; //set the top
    $root.animate({
        scrollTop: top //now scroll
    }, 500, function () {
        window.location.hash = href;
    });
    return false;
});

小提琴

于 2013-10-06T21:23:36.397 回答
1
var href = $(this).attr('href');

更新为评论

为了

scrollTop: $(href).offset().top

上班,

href

变量必须是页面上的一个元素。

所以如果你的链接像

<a href="#an_id_to_a_div">...</a>

没事的。

jquery dom对象创建

 $(dom_element) 

针对 html 标签、类、id 或现有的 Dom 对象(窗口、文档 ..)

于 2013-10-06T21:22:00.397 回答