使用 jquery 滚动到一个 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3432656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:26:54  来源:igfitidea点击:

Scroll to a div using jquery

jqueryscroll

提问by tshauck

so I have a page that has a fixed link bar on the side. I'd like to scroll to the different divs. Basically the page is just one long website, where I'd like to scroll to different divs using the menu box to the side.

所以我有一个页面,侧面有一个固定的链接栏。我想滚动到不同的 div。基本上该页面只是一个很长的网站,我想使用侧面的菜单框滚动到不同的 div。

Here is the jquery I have so far

这是我到目前为止的 jquery

$(document).ready(function() {
    $('#contactlink').click = function() {
        $(document).scrollTo('#contact');
    }
});

The issue is it is automatically going to the contact div when it loads, then when I press the #contactlinkin the menu it scrolls back to the top.

问题是它在加载时会自动转到联系人 div,然后当我按下#contactlink菜单中的 时,它会滚动回顶部。

EDIT: HTML

编辑:HTML

<!DOCTYPE html>

<html lang="en">

    <head>
    <meta charset="utf-8">

    <!-- jQuery-->
    <script src = "<?php echo base_url() ?>assets/js/jquery.js"></script>

    <!-- .js file-->
    <script src = "<?php echo base_url() ?>assets/js/pagetwo.js"></script>

    <link rel="stylesheet" type="text/css" href="<?php echo base_url()?>assets/css/reset.css" />    

    <!-- .css for page -->
    <link rel="stylesheet" type="text/css" href="<?php echo base_url()?>assets/css/pagetwo.css"/>                       

    <!-- page title-->
    <title><!-- Insert Title --></title>


</head>
<body>
    <div id="container">

        <div id="sidebar">
            <ul>
                <li><a id = "aboutlink" href="#">auck</a></li>
                <li><a id = "peojectslink" href="#">Projects</a></li>
                <li><a id = "resumelink" href="#">Resume</a></li>
                <li><a id = "contactlink" href="#">Contact</a></li>
            </ul>
        </div>

        <div id="content">
            <div class="" id="about">
                <p class="header">uck</p>
                <p class="info">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
            </div>
            <div class="sections"id="projects">
                <p class = "header">Projects</p>
                <p class="info">Projects</p>
            </div>
            <div class="sections" id="resume">
                <p class = "header">Resume</p>
                <p class="info">Resume</p>
            </div>
            <div class="sections" id="contacts">
                <p class = "header">Contact</p>
                <p class="info">Contact</p>
            </div>
        </div>
    </div>
</body>

Thanks for the help

谢谢您的帮助

回答by Peter Ajtai

First, your code does not contain a contactdiv, it has a contactsdiv!

首先,您的代码不包含contactdiv,它有一个contactsdiv!

In sidebar you have contactin the div at the bottom of the page you have contacts. I removed the final sfor the code sample. (you also misspelled the projectslinkid in the sidebar).

在侧边栏中,您contact在页面底部的 div 中有contacts。我删除了s代码示例的 final 。(您还在projectslink侧边栏中拼错了id)。

Second, take a look at some of the examples for clickon the jQuery reference page. You have to use click like, object.click( function() { // Your code here } );in order to bind a click event handler to the object.... Like in my example below. As an aside, you can also just trigger a click on an object by using it without arguments, like object.click().

其次,看一下jQuery 参考页面上单击的一些示例。您必须使用 click like,object.click( function() { // Your code here } );以便将 click 事件处理程序绑定到对象......就像我下面的例子一样。顺便说一句,您还可以通过不带参数的使用来触发对对象的单击,例如object.click().

Third, scrollTois a pluginin jQuery. I don't know if you have the plugin installed. You can't use scrollTo()without the plugin. In this case, the functionality you desire is only 2 lines of code, so I see no reason to use the plugin.

第三,scrollTo是jQuery中的插件。不知道你有没有安装插件。scrollTo()没有插件就不能使用。在这种情况下,您想要的功能只有 2 行代码,所以我认为没有理由使用该插件。

Ok, now on to a solution.

好的,现在进入解决方案。

The code below will scroll to the correct div if you click a link in the sidebar. The window does have to be big enough to allow scrolling:

如果您单击侧栏中的链接,下面的代码将滚动到正确的 div。窗口必须足够大以允许滚动:

// This is a functions that scrolls to #{blah}link
function goToByScroll(id) {
    // Remove "link" from the ID
    id = id.replace("link", "");
    // Scroll
    $('html,body').animate({
        scrollTop: $("#" + id).offset().top
    }, 'slow');
}

$("#sidebar > ul > li > a").click(function(e) {
    // Prevent a page reload when a link is pressed
    e.preventDefault();
    // Call the scroll function
    goToByScroll(this.id);
});

Live Example

现场示例

( Scroll to function taken from here)

(滚动到从这里获取的功能)



PS: Obviously you should have a compelling reason to go this route instead of using anchor tags <a href="#gohere">blah</a>... <a name="gohere">blah title</a>

PS:显然你应该有一个令人信服的理由走这条路而不是使用锚标签<a href="#gohere">blah</a>......<a name="gohere">blah title</a>

回答by jAndy

There is no .scrollTo()method in jQuery, but there is a .scrollTop()one. .scrollTopexpects a parameter, that is, the pixel value where the scrollbar should scroll to.

.scrollTo()jQuery 中没有方法,但有.scrollTop()一个。.scrollTop需要一个参数,即滚动条应该滚动到的像素值。

Example:

例子:

$(window).scrollTop(200);

will scroll the window (if there is enough content in it).

将滚动窗口(如果其中有足够的内容)。

So you can get this desired value with .offset()or .position().

因此,您可以使用.offset()或获得此所需值.position()

Example:

例子:

$(window).scrollTop($('#contact').offset().top);

This should scroll the #contactelement into view.

这应该将#contact元素滚动到视图中。

The non-jQuery alternate method is .scrollIntoView(). You can call that method on any DOM elementlike:

非 jQuery 替代方法是.scrollIntoView(). 您可以在任何DOM element类似的情况下调用该方法:

$('#contact')[0].scrollIntoView(true);

trueindicates that the element is positioned at the top whereas falsewould place it on the bottom of the view. The nice thing with the jQuery method is, you can even use it with fx functionslike .animate(). So you might smooth scroll something.

true表示该元素位于顶部,而false将其放置在视图的底部。jQuery 方法的好处是,您甚至可以将它与fx functionslike一起使用.animate()。因此,您可能会平滑滚动某些内容。

Reference: .scrollTop(), .position(), .offset()

参考:.scrollTop(), .position(), .offset()

回答by IT Vlogs

you can try :

你可以试试 :

$("#MediaPlayer").ready(function(){
    $("html, body").delay(2000).animate({
        scrollTop: $('#MediaPlayer').offset().top 
    }, 2000);
});

回答by Ryan

Add this little function and use it as so: $('div').scrollTo(500);

添加这个小函数并使用它: $('div').scrollTo(500);

jQuery.fn.extend(
{
  scrollTo : function(speed, easing)
  {
    return this.each(function()
    {
      var targetOffset = $(this).offset().top;
      $('html,body').animate({scrollTop: targetOffset}, speed, easing);
    });
  }
});

回答by christian

OK guys, this is a small solution, but it works fine.

好的,这是一个小解决方案,但效果很好。

suppose the following code:

假设以下代码:

<div id='the_div_holder' style='height: 400px; overflow-y: scroll'>
  <div class='post'>1st post</div>
  <div class='post'>2nd post</div>
  <div class='post'>3rd post</div>
</div>

you want when a new post is added to 'the_div_holder' then it scrolls its inner content (the div's .post) to the last one like a chat. So, do the following whenever a new .post is added to the main div holder:

您希望在将新帖子添加到“the_div_holder”时,它会将其内部内容(div 的 .post)滚动到最后一个,就像聊天一样。所以,每当一个新的 .post 添加到主 div 持有者时,请执行以下操作:

var scroll = function(div) {
    var totalHeight = 0;
    div.find('.post').each(function(){
       totalHeight += $(this).outerHeight();
    });
    div.scrollTop(totalHeight);
  }
  // call it:
  scroll($('#the_div_holder'));

回答by Sayyed Salman

First get the position of the div element upto which u want to scroll by jQuery position() method.
Example : var pos = $("div").position();
Then get the y cordinates (height) of that element with ".top" method.
Example : pos.top;
Then get the x cordinates of the that div element with ".left" method.
These methods are originated from CSS positioning.
Once we get x & y cordinates, then we can use javascript's scrollTo();method.
This method scrolls the document upto specific height & width.
It takes two parameters as x & y cordinates. Syntax : window.scrollTo(x,y);
Then just pass the x & y cordinates of the DIV element in the scrollTo()function.
Refer the example below ↓ ↓

首先通过 jQuery position() 方法获取你想要滚动到的 div 元素的位置。
示例:var pos = $("div").position();
然后使用“ .top”方法获取该元素的 y 坐标(高度)。
示例:pos.top;
然后使用“ .left”方法获取该 div 元素的 x坐标
这些方法起源于 CSS 定位。
一旦我们得到 x & y 坐标,那么我们就可以使用 javascript 的scrollTo(); 方法。
此方法将文档滚动到特定的高度和宽度。
它需要两个参数作为 x 和 y 坐标。语法:window.scrollTo(x,y);
然后只需在scrollTo()函数中传递 DIV 元素的 x & y 坐标。
参考下面的例子↓↓

<!DOCTYPE HTML>
    <html>
    <head>
        <title>
            Scroll upto Div with jQuery.
        </title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <script>
            $(document).ready(function () {
                $("#button1").click(function () {
                    var x = $("#element").position(); //gets the position of the div element...
                    window.scrollTo(x.left, x.top); //window.scrollTo() scrolls the page upto certain position....
                    //it takes 2 parameters : (x axis cordinate, y axis cordinate);
                });
            });
            </script>
    </head>
    <body>
        <button id="button1">
            Click here to scroll
        </button>

        <div id="element" style="position:absolute;top:200%;left:0%;background-color:orange;height:100px;width:200px;">
            The DIV element.
            </div>
        </body>
    </html>

回答by Armin Akhlagh

No need too these. Just simply add div idto href of a < a > tag

也不需要这些。只需简单地将div id添加到< a > 标签的 href

<li><a id = "aboutlink" href="#about">auck</a></li>

Just like that.

就这样。