【问题标题】:Scroll to specific tag name with specific class滚动到具有特定类的特定标签名称
【发布时间】:2015-04-28 20:41:51
【问题描述】:

这是我的 html 代码的样子:

<div class="code">
    <declaration class="2">
        toto
    </declaration>
    <identifier class="2">
        toto
    </identifier>
    <identifier class="3">
        toto
    </identifier>
    <identifier class="2">
        toto
    </identifier>
</div>

这是我的javascript:

function gotoDeclaration(){
    $(".code identifier").click(function goto() {
        var list = document.getElementsByClassName($(this).attr('class'));
        for (var i = 0; i < list.length; i++) {
            if (list[i].nodeName === 'declaration')
                $('html, body').animate(
                    {scrollTop: list[i].offset().top}, 
                    'fast');
            return false;
        }
    });
}

我想做的是,如果我点击一个带有标签名称标识符的元素,它会滚动到带有标签名称声明的元素,与标识符元素具有相同的类。

当我单击时没有任何反应。

该函数在其他一些工作函数之后被调用:

$(document).ready(function(){
gotoDeclaration();
highlightIdentifiers();
expandCollapse();
});

【问题讨论】:

  • 什么不起作用?点击后会发生什么?
  • 什么时候调用gotoDeclaration函数?
  • 当我点击时没有任何反应。该函数在其他一些工作函数之后被调用。
  • 一个简单任务的代码太多 - 发布一个简单的方法。

标签: jquery class scroll tagname


【解决方案1】:

执行list[i] 返回一个 HTML 元素。问题是您使用的是 jQuery 函数:list[i].offset()

要解决这个问题,请改用.eq

$('html, body').animate(
    {scrollTop: list.eq(i).offset().top}, 
    'fast');

还有一种更好的编码方式。既然已经加载了 jQuery,那就使用吧!

function gotoDeclaration(){
    $(".code identifier").click(function goto() {
        var list = $('declaration.'+$(this).attr('class'));
        $('html, body').animate(
             {scrollTop: list.offset().top}, 
             'fast');
    });
}

【讨论】:

    【解决方案2】:

    你为什么要遍历所有元素? 您不需要仅仅为了一个简单的任务。

    试试这个:

    function gotoDeclaration(){
        $(".code identifier").click(function goto() {
            var $dec = $('declaration.'+$(this).attr('class'));
            $('html, body').animate({scrollTop: $dec.offset().top}, 'fast');
        });
    }
    
    
    $(document).ready(function(){
      gotoDeclaration();
    });
    identifier,
    declaration { height:400px; display:block; }
    identifier { background-color:lightblue; cursor:pointer; }
    declaration { background-color:lightgreen; }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div class="code">
        <declaration class="2">
            declaration 2
        </declaration>
        <identifier class="2">
            identifier 2
        </identifier>
        <declaration class="3">
            declaration 3
        </declaration>
        <identifier class="3">
            identifier 3
        </identifier>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-09
      • 1970-01-01
      • 2015-07-17
      • 2021-02-06
      • 2020-11-05
      • 2022-01-13
      • 2012-12-04
      • 1970-01-01
      相关资源
      最近更新 更多