javascript - 如何滚动到 anchor 名称?

标签 javascript jquery html css

我有一个 Accordion 。单击 anchor 链接时,我想滚动到 Accordion 内的 anchor 名称。示例网址:http://swagatobhatta.com/accordion.html

我收到一个错误,如 Cannot read property 'top' of undefined

我查看了整个谷歌,也在 stackoverflow 中查看了这里。我几乎应用了所有给出的解决方案。我仍然无法解决这个问题

代码:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Testing accordion</title>
<link rel="stylesheet" type="text/css" href="test.css" />
</head>
<body>
Hello world
<a href="#anchor1">Anchor 1</a>
<br/>
<a href="#anchor2">Anchor 2</a>
<div>
Enthusiastically reconceptualize wireless technologies rather than pandemic e-business. Collaboratively deliver cross functional core competencies after economically sound services. Proactively build resource maximizing human capital before client-centric best practices. Efficiently simplify multifunctional functionalities and team building materials. Credibly morph cross-media partnerships without diverse quality vectors.</div>
<div class="accordionModule  ">
  <h3 class="title"> Credibly initiate market positioning e-commerce after web-enabled core competencies. Dramatically. </h3>
  <div class="panels">
    <div class="accordionPanel"> <a href="#" class="trigger">
      <h4 class="accordionTitle">Loreum 1</h4>
      </a>
      <div class="content richTextModule">
        <p>Efficiently evolve bricks-and-clicks human capital for focused intellectual capital. Compellingly brand state of the art information vis-a-vis backend channels. Appropriately empower high-payoff schemas whereas bricks-and-clicks processes. <a name="globally"></a>Globally drive resource sucking leadership and wireless products. Assertively monetize viral testing procedures without bleeding-edge e-markets.</p>
      </div>
    </div>
    <div class="accordionPanel"> <a href="#" class="trigger">
      <h4 class="accordionTitle">Test Links</h4>
      </a>
      <div class="content richTextModule">
        <p>This is an external link to<a href="http://swagatobhatta.com/accordion.html">Where am i</a></p>
        <p>&nbsp;</p>
        <p>My</p>
      </div>
    </div>
    <div class="accordionPanel"> <a href="#" class="trigger">
      <h4 class="accordionTitle">Internal anchor test</h4>
      </a>
      <div class="content richTextModule">
        <p>This is <a href="http://swagatobhatta.com/accordion.html">internal anchor test</a></p>
        <p><a name="anchor1"></a>anchor&nbsp;</p>
      </div>
    </div>
    <div class="accordionPanel"> <a href="#" class="trigger">
      <h4 class="accordionTitle">Anchor inside</h4>
      </a>
      <div class="content richTextModule">
           <p>&nbsp;</p>
        <p>&nbsp;</p>
        <p>Hello <a name="anchor2"></a>world</p>
        <p>&nbsp;</p>
        <p>&nbsp;</p>

      </div>
    </div>
  </div>
</div>

<div>
Interactively brand professional convergence vis-a-vis just in time niches. Credibly seize wireless channels rather than corporate intellectual capital. Seamlessly recaptiualize customer directed products without cross functional supply chains. Rapidiously administrate progressive technology before cross functional core competencies. Objectively orchestrate integrated total linkage before dynamic schemas.


Enthusiastically reconceptualize wireless technologies rather than pandemic e-business. Collaboratively deliver cross functional core competencies after 
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
(function (_this, $) {
    _this.accordionSpeed = 400;
    _this.initialise = function () {
        $(function () {
            bindAccordionTriggers();
        });

        return _this;
    }

    var bindAccordionTriggers = function() {
        $('.accordionModule .accordionPanel .trigger').on('click', function(e) {
            e.preventDefault();

            var $parentPanel = $(this).parents('.accordionPanel');

            if( $parentPanel.hasClass('open') ) {
                $parentPanel.removeClass('open');
                $parentPanel.find('.content').slideUp(_this.accordionSpeed);
            }
            else {
                var $module = $(this).parents('.accordionModule');
                if($module.hasClass('open-single-only')) {
                    var $openPanel = $module.find('.accordionPanel.open');
                    $openPanel.find('.content').slideUp();
                    $openPanel.removeClass('open');
                }

                $parentPanel.find('.content').slideDown(_this.accordionSpeed);
                $parentPanel.addClass('open');
            }
        });


        function scrollToAnchor(aid){
            var aTag = $("a[name='"+ aid +"']");
            $('html,body').animate({scrollTop: aTag.offset().top},'slow');
        }



        $(window).on('load hashchange',function(event){
            var hash = window.location.hash;
            var hashName = hash && hash.replace('#','');
                event.preventDefault();

            if (hashName) {
                //document.getElementsByName ("#anchor1").scrollIntoView();
                scrollToAnchor('hashName');

                $('.accordionModule .accordionPanel .content a').filter(function(){
                    //return this.hash === hash;
                    return this.name === hashName;
                }).closest('.accordionPanel').find('.trigger').click()

            }
        });

    }

    // Initialise & assign to global scope
    window.AccordionModule = _this.initialise();
})(window.AccordionModule || {}, jQuery);
</script>
</body>
</html>

最佳答案

代替:

<p><a name="anchor1"></a>anchor&nbsp;</p>
<p>Hello <a name="anchor2"></a>world</p> 

尝试拥有:

<p id="anchor1">ANCHOR 1 HERE</p>
<p id="anchor2">ANCHOR 2 HERE</p> 

“滚动到 anchor ”的脚本也比您目前拥有的脚本简单得多。这是一个片段:

jQuery(function($) {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

演示:

http://codepen.io/Himechi90/pen/wKepep

祝你好运!

关于javascript - 如何滚动到 anchor 名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33029221/

相关文章:

javascript - 如何在 jest 的覆盖范围内忽略由 jest 生成的快照?

javascript - 单击其他 href 后,href 的 onclick 中断

javascript - 使用 jquery 获取所有浏览器中的宽度中心

jquery - 如何通过选择和输入来监听表单的所有变化?

javascript - Vue js如何在prop更改时调用方法

javascript - 为什么 signup 和 me 总是在 mutation 和 query 类型中?

javascript - 将元素添加到 dom 并使用 jquery 应用类不应用 css3 转换

jquery - 在 JQuery DataTable 中的按钮单击中传递 ID

javascript - 尝试从一个 JS 文件中包含多个 JS 文件时出错

javascript - 检测 Angular JavaScript promise 链中是否存在下一个处理程序