0

I've searched the web at length for a solution and come very close, but I'm hoping someone smarter than I can perfect this. When I click a div, I would like the top of said div to scroll to the top of the browser window. The current code snippet causes a parent div with the id "centered" to scroll to the top, but I would like each child div to scroll to its own top without having to write out an instance for every single div.

toggle:function(divid){ //public method
if (typeof divid=="object")
    divid=divid[0]
this.showhide(divid, "toggle")
$("html, body").animate({scrollTop:$('#centered').position().top}, 600);

}

Can anyone point out what I'm missing?

4

1 回答 1

0

在不知道“分”代表什么的情况下,这是一个相当通用的示例,可能不会直接适合您的场景。但是,假设 'divid' 是 id 值或代表 div 的对象,您应该能够执行以下操作:

toggle:function(divid) {
    if (typeof divid == 'object') {
        divid = $(divid[0]); // Assumes a jQuery object (not very robust)
    } else {
        divid = $('#' + divid);
    }

    this.showhide(divid, "toggle"); // May break depending if it accepts the jQuery object
    $('html, body').animate({ scrollTop: divid.offset().top }, 600);
}

如果 'this' 是对相关 div 的引用,您可以只换入 $(this) 而不是使用 divid。

请注意,此代码不是很健壮,因此应正确更改以说明真正的除数。另请注意 - 不要忘记您的分号。

于 2013-03-29T01:51:24.233 回答