ChatGPT解决这个技术问题 Extra ChatGPT

如何使用 jQuery 滚动到特定项目?

我有一个带有垂直滚动条的大桌子。我想使用 jQuery/JavaScript 滚动到此表中的特定行。

是否有内置方法可以做到这一点?

Here is a little example to play with.

div { 宽度:100px;高度:70px;边框:1px 纯蓝色;溢出:自动; }

1
2
3
4
5
6
7
8
9


S
Syscall

死的简单。不需要插件。

var $container = $('div'),
    $scrollTo = $('#row_8');

$container.scrollTop(
    $scrollTo.offset().top - $container.offset().top + $container.scrollTop()
);

// Or you can animate the scrolling:
$container.animate({
    scrollTop: $scrollTo.offset().top - $container.offset().top + $container.scrollTop()
});​

这是一个working example

Documentation for scrollTop


如果容器有滚动条,则需要考虑 scrollTop:scrollTo.offset().top - container.offset().top + container.scrollTop()
您可以使用 $(document).scrollTop(value) 滚动整个窗口 - 底层 jquery 代码为您解决浏览器问题。
如果您希望 scrollTo 居中而不是顶部:scrollTo.offset().top - container.offset().top + container.scrollTop() - (container.height()/2)
element.scrollIntoView() - 这就是所需要的。动画是标准化的。请参阅developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
请注意,代码块的最后有一个“不可见”字符。该字符在 Edge、chrome 中被认为是无效的。 - 复制粘贴
L
Luke Wenke

我意识到这并不能回答在容器中滚动,但人们发现它很有用,所以:

$('html,body').animate({scrollTop: some_element.offset().top});

我们同时选择 html 和 body,因为文档滚动条可能在其中一个上,并且很难确定哪个。对于现代浏览器,您可以使用 $(document.body)

或者,要转到页面顶部:

$('html,body').animate({scrollTop: 0});

或者没有动画:

$(window).scrollTop(some_element.offset().top);

或者...

window.scrollTo(0, some_element.offset().top); // native equivalent (x, y)

你好@infensus你能给我一个这个原因我的工作不工作的例子吗?我用 var section2=$('#section-2'); $('html,body').animate({scrollTop: section2.offset().top});
看起来不错 - 你确定 section2 存在吗?做 console.log(section2.length);并确保它不为 0。稍后将举例说明。
为什么是$('html,body')?他只需要在特定的容器中。接受的答案对我来说更好。我有类似的情况,例如所问的问题,而您的回答对我不起作用。
@Petroff 奇怪的是,当我写这篇文章时,我没有注意到元素在滚动容器中。我会保留我的答案,因为由于问题标题,人们从谷歌搜索来到这里滚动正文
F
Fredrik Stolpe

我同意 Kevin 和其他人的观点,为此使用插件是没有意义的。

window.scrollTo(0, $("#element").offset().top);

对于应该非常简单的事情,我花了很长时间在网上的其他解决方案上,但是这个简单的一个班轮正是我所需要的。
需要注意的是,这种方式适用于整个窗口。如果您想滚动具有溢出的内容:滚动那么这将不起作用。
m
miken32

我自己设法做到了。不需要任何插件。查看我的 gist

// Replace #fromA with your button/control and #toB with the target to which     
// You wanna scroll to. 
//
$("#fromA").click(function() {
    $("html, body").animate({ scrollTop: $("#toB").offset().top }, 1500);
});

你的一句话要点,加上动画,正是我所需要的。谢谢!
No need for any plugins ??但是你使用 jQuery!这是一个巨大的图书馆,甚至不是一个插件。
我提到除了 jquery 库参考之外,您不需要添加参考。加上 jquery 是一种行业标准。你为什么不使用它?如果没有 jquery,这可能是完全可行的,但它仍然需要有人为解析部分编写大量代码。感觉适得其反。编写一个完整的插件只是为了滚动到一个令人毛骨悚然的 div 感觉适得其反。
A
Alex Jolig

您可以在 javascript 中使用 scrollIntoView() 方法。给id.scrollIntoView();

例如

row_5.scrollIntoView();

如何制作动画?
无需动画。当您使用 scrollIntoView() 时,控件将自动滚动以使其显示在视图中。
Z
Zev Spitz

您可以使用 the jQuery scrollTo plugin 插件:

$('div').scrollTo('#row_8');

该链接不再可用。你能更新一下吗?
S
Syscall

滚动元素到容器中心

将元素带到容器的中心。

DEMO on CODEPEN

JS

function scrollToCenter() {
  var container = $('.container'),
    scrollTo = $('.5');

  container.animate({
    //scrolls to center
    scrollTop: scrollTo.offset().top - container.offset().top + scrollTo.scrollTop() - container.height() / 2
  });
}

HTML

<div class="container">
   <div class="1">
    1
  </div>
  <div class="2">
    2
  </div>
  <div class="3">
    3
  </div>
  <div class="4">
    4
  </div>
  <div class="5">
    5
  </div>
  <div class="6">
    6
  </div>
  <div class="7">
    7
  </div>
  <div class="8">
    8
  </div>
  <div class="9">
    9
  </div>
  <div class="10">
    10
  </div>


</div>
<br>
<br>
<button id="scroll" onclick="scrollToCenter()">
  Scroll
</button>

css

.container {
  height: 60px;
  overflow-y: scroll;
  width 60px;
  background-color: white;
}

它不精确到中心,但你不会在更大的元素上识别它。


M
MD Ashik

您可以通过 jQuery 和 JavaScript 滚动只需要两个元素 jQuery 和这个 JavaScript 代码:

$(function() {
  // Generic selector to be used anywhere
  $(".js-scroll-to-id").click(function(e) {

    // Get the href dynamically
    var destination = $(this).attr('href');

    // Prevent href=“#” link from changing the URL hash (optional)
    e.preventDefault();

    // Animate scroll to destination
    $('html, body').animate({
      scrollTop: $(destination).offset().top
    }, 1500);
  });
});

$(function() { // 通用选择器可以在任何地方使用 $(".js-scroll-to-id").click(function(e) { // 动态获取 href var destination = $(this).attr ('href'); // 防止 href=“#” 链接更改 URL 哈希(可选) e.preventDefault(); // 动画滚动到目标 $('html, body').animate({ scrollTop: $ (目标).offset().top }, 1500); }); }); #pane1 { 背景:#000;宽度:400px;高度:400px; } #pane2 { 背景:#ff0000;宽度:400px;高度:400px; } #pane3 { 背景:#ccc;宽度:400px;高度:400px; }


S
Syscall

不知道为什么没有人说显而易见的,因为有一个内置的 javascript scrollTo 函数:

scrollTo( $('#element').position().top );

Reference


scrollTo 需要两个参数,你只写了一个。
...并在窗口对象上调用它。
N
Nlinscott

我结合了其他人发布的内容。它简单流畅

 $('#myButton').click(function(){
        $('html, body').animate({
            scrollTop: $('#scroll-to-this-element').position().top },
            1000
        );
    });

@AnriëtteMyburgh 我不确定 position() 是否适用于所有浏览器。你有没有在其他人身上试过,看看它是否有效?或者我可以看看你正在使用的代码,看看是否还有其他问题?
S
Syscall

与这里大多数人的建议相反,如果您想为移动设置动画,我建议您使用插件。仅仅为 scrollTop 设置动画还不足以提供流畅的用户体验。有关原因,请参见 my answer here

多年来我尝试了许多插件,但最终自己编写了一个。您可能想试一试:jQuery.scrollable。使用它,滚动动作变成

$container.scrollTo( targetPosition );

但这还不是全部。我们也需要固定目标位置。您在其他答案中看到的计算,

$target.offset().top - $container.offset().top + $container.scrollTop()

大部分有效,但并不完全正确。它没有正确处理滚动容器的边框。目标元素向上滚动太多,超出了边框的大小。 Here is a demo.

因此,计算目标位置的更好方法是

var target = $target[0], 
    container = $container[0];

targetPosition = $container.scrollTop() + target.getBoundingClientRect().top - container.getBoundingClientRect().top - container.clientTop;

再次查看 at the demo 以了解它的实际效果。

对于返回目标位置并适用于窗口和非窗口滚动容器的函数,请随意使用 this gist。那里的评论解释了如何计算位置。

一开始,我说过最好使用动画滚动插件。但是,如果您想在没有过渡的情况下跳转到目标,则不需要插件。请参阅 answer by @James,但如果容器周围有边框,请确保正确计算目标位置。


m
martinh_kentico

对于它的价值,这就是我如何设法为一个可以在带有滚动的 DIV 内的通用元素实现这种行为(不知道容器)

它创建一个目标元素高度的假输入,然后将焦点放在它上面,无论您在可滚动层次结构中有多深,浏览器都会处理其余部分。奇迹般有效。

var $scrollTo = $('#someId'),
inputElem = $('<input type="text"></input>');

$scrollTo.prepend(inputElem);
inputElem.css({
  position: 'absolute',
  width: '1px',
  height: $scrollTo.height()
});
inputElem.focus();
inputElem.remove();

L
LBes

我做了这个组合。它为我工作。但是如果单击移动该 div 大小太大,场景滚动不会向下到这个特定的 div,则会面临一个问题。

 var scrollDownTo =$("#show_question_" + nQueId).position().top;
        console.log(scrollDownTo);
        $('#slider_light_box_container').animate({
            scrollTop: scrollDownTo
            }, 1000, function(){
        });

        }