我有一份问题清单。当我点击第一个问题时,它会自动把我带到页面底部的特定元素。

我如何用jQuery做到这一点?


当前回答

来晚了,但这里有一些简单的javascript代码,可以将任何元素滚动到底部:

function scrollToBottom(e) {
  e.scrollTop = e.scrollHeight - e.getBoundingClientRect().height;
}

其他回答

如果您想向下滚动到特定元素,这是一种简单的方法。

当您想向下滚动时,请调用此函数。

function scrollDown() { document.getElementById('scroll').scrollTop = document.getElementById('scroll').scrollHeight } ul{ height: 100px; width: 200px; overflow-y: scroll; border: 1px solid #000; } <ul id='scroll'> <li>Top Here</li> <li>Something Here</li> <li>Something Here</li> <li>Something Here</li> <li>Something Here</li> <li>Something Here</li> <li>Something Here</li> <li>Something Here</li> <li>Something Here</li> <li>Something Here</li> <li>Bottom Here</li> <li style="color: red">Bottom Here</li> </ul> <br /> <button onclick='scrollDown()'>Scroll Down</button>

我也遇到过同样的问题。对于我来说,在一个时间点上,div的元素没有完全加载,scrollTop属性是用scrollHeight的当前值初始化的,这不是scrollHeight的正确结束值。

我的项目在Angular 8中,我所做的是:

我使用viewchild来获取.ts文件中的元素。 我已经继承了AfterViewChecked事件,并在那里放置了一行代码,其中声明viewchild元素必须将scrollTop值的值scrollHeight (this.viewChildElement.nativeElement。scrollTop = this.viewChildElement.nativeElement.scrollHeight;)

AfterViewChecked事件触发了几次,它最终从scrollHeight中获得了正确的值。

你可以在任何需要调用它的地方使用这个函数:

function scroll_to(div){
   if (div.scrollTop < div.scrollHeight - div.clientHeight)
        div.scrollTop += 10; // move down

}

jquery.com ScrollTo

你也可以用动画来做这个,非常简单

$('html, body').animate({
   scrollTop: $('footer').offset().top
   //scrollTop: $('#your-id').offset().top
   //scrollTop: $('.your-class').offset().top
}, 'slow');

希望有所帮助, 谢谢你!

有时页面会滚动到底部(例如在社交网络中),向下滚动到最后(页面的最终底部),我使用这个脚本:

var scrollInterval = setInterval(function() { 
    document.documentElement.scrollTop = document.documentElement.scrollHeight;
}, 50);

如果你是在浏览器的javascript控制台,它可能是有用的,能够停止滚动,所以添加:

var stopScroll = function() { clearInterval(scrollInterval); };

然后使用stopScroll();。

如果你需要滚动到特定的元素,使用:

var element = document.querySelector(".element-selector");
element.scrollIntoView();

或通用脚本自动滚动到特定的元素(或停止页面滚动间隔):

var notChangedStepsCount = 0;
var scrollInterval = setInterval(function() {
    var element = document.querySelector(".element-selector");
    if (element) { 
        // element found
        clearInterval(scrollInterval);
        element.scrollIntoView();
    } else if((document.documentElement.scrollTop + window.innerHeight) != document.documentElement.scrollHeight) { 
        // no element -> scrolling
        notChangedStepsCount = 0;
        document.documentElement.scrollTop = document.documentElement.scrollHeight;
    } else if (notChangedStepsCount > 20) { 
        // no more space to scroll
        clearInterval(scrollInterval);
    } else {
        // waiting for possible extension (autoload) of the page
        notChangedStepsCount++;
    }
}, 50);