如何使用JavaScript滚动到元素?

时间:2011-02-15 18:02:08

标签: javascript html

我正在尝试将页面移动到<div>元素。

我尝试了下一个代码无济于事:

document.getElementById("divFirst").style.visibility = 'visible';
document.getElementById("divFirst").style.display = 'block';

19 个答案:

答案 0 :(得分:148)

scrollIntoView效果很好:

document.getElementById("divFirst").scrollIntoView();

MDN文档中的完整参考:
https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollIntoView

答案 1 :(得分:96)

您可以使用锚点来“聚焦”div。即:

<div id="myDiv"></div>

然后使用以下javascript:

// the next line is required to work around a bug in WebKit (Chrome / Safari)
location.href = "#";
location.href = "#myDiv";

答案 2 :(得分:90)

你的问题和答案看起来不一样。我不知道自己是不是错了,但对于那些谷歌并且到达这里的人,我的答案如下:

  1. My answer on stackoverflow
  2. A similar question
  3. 我的回答解释说:

    这是一个简单的javascript

    当您需要将屏幕滚动到具有id =“yourSpecificElementId”

    的元素时,请调用此方法
    window.scroll(0,findPos(document.getElementById("yourSpecificElementId")));
    

    即。对于上述问题,如果打算将屏幕滚动到id为'divFirst'的div

    代码为:window.scroll(0,findPos(document.getElementById("divFirst")));

    你需要这个功能才能正常工作:

    //Finds y value of given object
    function findPos(obj) {
        var curtop = 0;
        if (obj.offsetParent) {
            do {
                curtop += obj.offsetTop;
            } while (obj = obj.offsetParent);
        return [curtop];
        }
    }
    

    屏幕将滚动到您的特定元素。

答案 3 :(得分:30)

我一直在研究这个问题,我认为这个问题在某种程度上是最自然的方式。当然,这是我个人最喜欢的卷轴。 :)

from collections import Counter
import string
tweet = input('Tweet: ')
lis = tweet.lower().strip().split()
lis_hash = []

while tweet:
  for i in lis:
    i = i.rstrip(string.punctuation)
    if i[0] == '#':
      lis_hash.append(i)
  tweet = input('Tweet: ')
  lis = tweet.lower().strip().split()

ans = Counter(lis_hash)
for i in ans:
  print(i,ans[i])

答案 4 :(得分:7)

试试这个:

var divFirst = document.getElementById("divFirst");
divFirst.style.visibility = 'visible'; 
divFirst.style.display = 'block';  
divFirst.tabIndex = "-1";  
divFirst.focus();

例如@:

  

http://jsfiddle.net/Vgrey/

答案 5 :(得分:6)

要滚动到给定元素,只需在下面创建这个仅限javascript的解决方案。

简单用法:

EPPZScrollTo.scrollVerticalToElementById('signup_form', 20);

引擎对象(您可以使用过滤器,fps值):

/**
 *
 * Created by Borbás Geri on 12/17/13
 * Copyright (c) 2013 eppz! development, LLC.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */


var EPPZScrollTo =
{
    /**
     * Helpers.
     */
    documentVerticalScrollPosition: function()
    {
        if (self.pageYOffset) return self.pageYOffset; // Firefox, Chrome, Opera, Safari.
        if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Internet Explorer 6 (standards mode).
        if (document.body.scrollTop) return document.body.scrollTop; // Internet Explorer 6, 7 and 8.
        return 0; // None of the above.
    },

    viewportHeight: function()
    { return (document.compatMode === "CSS1Compat") ? document.documentElement.clientHeight : document.body.clientHeight; },

    documentHeight: function()
    { return (document.height !== undefined) ? document.height : document.body.offsetHeight; },

    documentMaximumScrollPosition: function()
    { return this.documentHeight() - this.viewportHeight(); },

    elementVerticalClientPositionById: function(id)
    {
        var element = document.getElementById(id);
        var rectangle = element.getBoundingClientRect();
        return rectangle.top;
    },

    /**
     * Animation tick.
     */
    scrollVerticalTickToPosition: function(currentPosition, targetPosition)
    {
        var filter = 0.2;
        var fps = 60;
        var difference = parseFloat(targetPosition) - parseFloat(currentPosition);

        // Snap, then stop if arrived.
        var arrived = (Math.abs(difference) <= 0.5);
        if (arrived)
        {
            // Apply target.
            scrollTo(0.0, targetPosition);
            return;
        }

        // Filtered position.
        currentPosition = (parseFloat(currentPosition) * (1.0 - filter)) + (parseFloat(targetPosition) * filter);

        // Apply target.
        scrollTo(0.0, Math.round(currentPosition));

        // Schedule next tick.
        setTimeout("EPPZScrollTo.scrollVerticalTickToPosition("+currentPosition+", "+targetPosition+")", (1000 / fps));
    },

    /**
     * For public use.
     *
     * @param id The id of the element to scroll to.
     * @param padding Top padding to apply above element.
     */
    scrollVerticalToElementById: function(id, padding)
    {
        var element = document.getElementById(id);
        if (element == null)
        {
            console.warn('Cannot find element with id \''+id+'\'.');
            return;
        }

        var targetPosition = this.documentVerticalScrollPosition() + this.elementVerticalClientPositionById(id) - padding;
        var currentPosition = this.documentVerticalScrollPosition();

        // Clamp.
        var maximumScrollPosition = this.documentMaximumScrollPosition();
        if (targetPosition > maximumScrollPosition) targetPosition = maximumScrollPosition;

        // Start animation.
        this.scrollVerticalTickToPosition(currentPosition, targetPosition);
    }
};

答案 6 :(得分:5)

这是一个可以包含那些固定标题的可选偏移量的函数。无需外部库。

function scrollIntoView(selector, offset = 0) {
  window.scroll(0, document.querySelector(selector).offsetTop - offset);
}

您可以使用JQuery获取元素的高度并滚动到它。

var headerHeight = $('.navbar-fixed-top').height();
scrollIntoView('#some-element', headerHeight)

更新2018年3月

不使用JQuery滚动到此答案

scrollIntoView('#answer-44786637', document.querySelector('.top-bar').offsetHeight)

答案 7 :(得分:3)

您可以将焦点设置为element。它比scrollIntoView

更好

node.setAttribute('tabindex', '-1')

node.focus()

node.removeAttribute('tabindex')

答案 8 :(得分:2)

我认为如果你向你的div添加一个tabindex,它将能够获得焦点:

<div class="divFirst" tabindex="-1">
</div>

我不认为它有效,tabindex只能应用于a,area,button,input,object,select和textarea。但试一试。

答案 9 :(得分:2)

焦点只能在交互元素上设置... Div仅代表页面的逻辑部分。

也许您可以设置div周围的边框或更改它的颜色以模拟焦点。是的,Visiblity不是焦点。

答案 10 :(得分:2)

即使是使用动画效果,最佳,最短答案:

var scrollDiv = document.getElementById("myDiv").offsetTop;
window.scrollTo({ top: scrollDiv, behavior: 'smooth'});

如果您有固定的导航栏,只需从顶部值中减去其高度,所以如果您固定的导航栏高度为70px,则第2行如下所示:

window.scrollTo({ top: scrollDiv-70, behavior: 'smooth'});

说明: 第1行获取元素位置 第2行滚动到元素位置; behavior属性可添加平滑的动画效果

答案 11 :(得分:1)

类似于@caveman的解决方案

const element = document.getElementById('theelementsid');

if (element) {
    window.scroll({
        top: element.scrollTop,
        behavior: 'smooth',
    }) 
}

答案 12 :(得分:0)

我们可以通过3种方法实现:

注意:

“自动滚动” =>特定元素

“ scrollable-div” =>可滚动区域div

方法1:

document.querySelector('.automatic-scroll').scrollIntoView({
     behavior: 'smooth'
});

方法2:

location.href = "#automatic-scroll";

方法3:

$('#scrollable-div').animate({
   scrollTop: $('#automatic-scroll').offset().top - $('#scrollable-div').offset().top + 
   $('#scrollable-div').scrollTop()
})

重要通知 :如果可滚动区域的高度为“ 自动”,则方法1和方法2将非常有用。如果我们使用“ calc(100vh-200px)”之类的可滚动区域高度,则方法3很有用。

答案 13 :(得分:0)

由于行为“流畅”在Safari,Safari ios,资源管理器中不起作用。我通常会利用requestAnimationFrame编写一个简单的函数

(function(){
    var start;
    var startPos = 0;

    //Navigation scroll page to element
    function scrollTo(timestamp, targetTop){
      if(!start) start = timestamp
      var runtime = timestamp - start
      var progress = Math.min(runtime / 700, 1)

      window.scroll(0, startPos + (targetTop * progress) )

      if(progress >= 1){
        return;
      }else {
        requestAnimationFrame(function(timestamp){
            scrollTo(timestamp, targetTop)
        })
      }
   };

  navElement.addEventListener('click', function(e){

    var target = e.target  //or this 
    var targetTop = _(target).getBoundingClientRect().top
    startPos = window.scrollY

    requestAnimationFrame(function(timestamp){
        scrollTo(timestamp, targetTop)
    })
  }

})();

答案 14 :(得分:0)

我经常用来将容器滚动到其内容的方法。

/**
@param {HTMLElement} container : element scrolled.
@param {HTMLElement} target : element where to scroll.
@param {number} [offset] : scroll back by offset
*/
var scrollAt=function(container,target,offset){
    if(container.contains(target)){
        var ofs=[0,0];
        var tmp=target;
        while (tmp!==container) {
            ofs[0]+=tmp.offsetWidth;
            ofs[1]+=tmp.offsetHeight;
            tmp=tmp.parentNode;
        }
        container.scrollTop = Math.max(0,ofs[1]-(typeof(offset)==='number'?offset:0));
    }else{
        throw('scrollAt Error: target not found in container');
    }
};

如果您希望全局覆盖,也可以执行以下操作:

HTMLElement.prototype.scrollAt=function(target,offset){
    if(this.contains(target)){
        var ofs=[0,0];
        var tmp=target;
        while (tmp!==this) {
            ofs[0]+=tmp.offsetWidth;
            ofs[1]+=tmp.offsetHeight;
            tmp=tmp.parentNode;
        }
        container.scrollTop = Math.max(0,ofs[1]-(typeof(offset)==='number'?offset:0));
    }else{
        throw('scrollAt Error: target not found in container');
    }
};

答案 15 :(得分:0)

经过四处看看后,这才是我的最终成果:

  1. 在你的dom中找到/找到有滚动条的div。 对我来说,它看起来像这样: “div class =”table_body table_body_div“scroll_top =”0“scroll_left =”0“style =”width:1263px;身高:499px;“

  2. 我找到了这个xpath:// div [@ class ='table_body table_body_div']

  3. 使用JavaScript执行这样的滚动: (JavascriptExecutor)驱动程序).executeScript(“arguments [0] .scrollLeft = arguments [1];”,element,2000);

  4. 2000是我想要向右滚动的像素数。 如果要向下滚动div,请使用scrollTop而不是scrollLeft。

    注意:我尝试使用scrollIntoView但它无法正常工作,因为我的网页有多个div。如果您只有一个焦点所在的主窗口,它将起作用。 如果您不想使用我不想要的jQuery,这是我遇到的最佳解决方案。

答案 16 :(得分:0)

你无法专注于div。您只能关注该div中的输入元素。此外,您需要使用element.focus()而不是display()

答案 17 :(得分:-1)

尝试此功能

function navigate(divId) {
$j('html, body').animate({ scrollTop: $j("#"+divId).offset().top }, 1500);
}

将div id作为参数传递它将起作用我已经使用它

答案 18 :(得分:-1)

如果你想使用html,你可以使用它:

a href="samplewebsite.com/subdivision.html#id

并使其成为指向特定元素ID的html链接。它基本上是getElementById html版本。

相关问题