平滑滚动jQuery不起作用 - 无法读取未定义的属性“top”

时间:2018-04-08 04:36:01

标签: javascript jquery html

我花了好几个小时试图弄清楚它为什么不起作用。基本上我只想让我页面上的滚动顺畅。

这是我的代码:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<header>
    <div class="my-name-header">
        <img src="people.png" class="astro-man-header">
        <h2>Itzik Shaoulian</h2>
    </div>
    <div class="nav-options">
        <nav>
            <ul class="list-options">
                <li class="option-name"><a href="#main-opening" class="nav-content">Home</a></li>
                <li class="option-name"><a href="#about-content" class="nav-content">About</a></li>
                <li class="option-name"><a href="#portfolio-content" class="nav-content">Portfolio</a></li>
                <li class="option-name"><a href="#skills-content" class="nav-content">Skills</a></li>
                <li class="option-name"><a href="#contact-content" class="nav-content">Contact</a></li>
                <li class="option-name"><a href="#" class="resume-header" class="nav-content">Resume</a></li>
            </ul>
        </nav>
    </div>
</header>
{{1}}

1 个答案:

答案 0 :(得分:1)

您需要从<a>代码中获取href,而不是<li>代码。

您可以使用find()功能

来实现此功能
let linkRef = $(this).find('a').attr('href');

我假设这将向下滚动到另一个html元素。但我不知道,可能是错的,对不起

希望这会有所帮助:)

&#13;
&#13;
$(document).ready(function() {
    var scrollLink = $('.option-name');
    scrollLink.click(function(e){
       e.preventDefault();
       let linkRef = $(this).find('a').attr('href');
       console.log(linkRef);//Log href
      
      //From this point, the full HTML is needed for operation
      // let position = $(linkRef).offset().top;
    	//$('html, body').animate({
    		//scrollTop : position
    		//}, 500)
    })
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<header>
    <div class="my-name-header">
        <img src="people.png" class="astro-man-header">
        <h2>Itzik Shaoulian</h2>
    </div>
    <div class="nav-options">
        <nav>
            <ul class="list-options">
                <li class="option-name"><a href="#main-opening" class="nav-content">Home</a></li>
                <li class="option-name"><a href="#about-content" class="nav-content">About</a></li>
                <li class="option-name"><a href="#portfolio-content" class="nav-content">Portfolio</a></li>
                <li class="option-name"><a href="#skills-content" class="nav-content">Skills</a></li>
                <li class="option-name"><a href="#contact-content" class="nav-content">Contact</a></li>
                <li class="option-name"><a href="#" class="resume-header" class="nav-content">Resume</a></li>
            </ul>
        </nav>
    </div>
</header>
&#13;
&#13;
&#13;