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多くのメニュー項目にないセレクターを取得しようとしています。

すなわち:

    <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 オブジェクト ( window 、 document .. ) をターゲットにします。

于 2013-10-06T21:22:00.397 に答える