2016-10-18 30 views
0

您好得到這個訊息: 遺漏的類型錯誤:無法未定義遺漏的類型錯誤:無法讀取未定義的偏移()屬性「頂」頂部

'scrollTop': $target.offset().top - 60 

代碼塊的讀取屬性「頂」:

$('.btn-circle-cover').on('click',function (e) { 
    e.preventDefault(); 
    var target = this.hash, 
    $target = $(target); 
    $('html, body').stop().animate({ 
     'scrollTop': $target.offset().top - 60 
    }, 2200, 'swing', function() { 
     window.location.hash = target; 
    }); 
}); 
+0

'$(this.hash)'是一個無效jQuery選擇。你的意思是'$(this)'? – Li357

回答

0

this.hash不是有效的,因爲this將代表<button>這不會有href。而是遍歷到使用.parentNode具有href屬性的父元素,並使用.hash獲取href的散列。

實施例:

$('.btn-circle-cover').on('click', function(e) { 
 
    e.preventDefault(); 
 
    var target = this, 
 
    $target = $(target); 
 
    $('html, body').stop().animate({ 
 
    'scrollTop': $target.offset().top - 60 
 
    }, 2200, 'swing', function() { 
 
    console.log('hash is: ', e.currentTarget.parentNode.hash) 
 
    window.location.hash = e.currentTarget.parentNode.hash; 
 
    }); 
 
});
body { 
 
    height: 4000px; 
 
} 
 
button { 
 
    margin-top: 3000px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p>Scroll Down</p> 
 
<a href="#hdsf"> 
 
    <button class="btn-circle-cover">Click here</button> 
 
</a>

相關問題