Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/437.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将HTML页面滚动到给定的锚?_Javascript_Jquery_Html_Scroll_Anchor - Fatal编程技术网

Javascript 如何将HTML页面滚动到给定的锚?

Javascript 如何将HTML页面滚动到给定的锚?,javascript,jquery,html,scroll,anchor,Javascript,Jquery,Html,Scroll,Anchor,我想让浏览器通过使用JavaScript将页面滚动到给定的锚定位置 我在HTML代码中指定了名称或id属性: <a name="anchorName">..</a> 。。 或 。。 我希望通过导航到http://server.com/path#anchorName。应滚动页面,使定位点靠近页面可见部分的顶部。您可以使用jQuerys和滚动顶部。像 $(document.body).animate({ 'scrollTop': $('#anchorNam

我想让浏览器通过使用JavaScript将页面滚动到给定的锚定位置

我在HTML代码中指定了
名称
id
属性:

 <a name="anchorName">..</a>
。。

。。
我希望通过导航到
http://server.com/path#anchorName
。应滚动页面,使定位点靠近页面可见部分的顶部。

您可以使用jQuerys和
滚动顶部。像

$(document.body).animate({
    'scrollTop':   $('#anchorName2').offset().top
}, 2000);
示例链接:

如果不想设置动画,请使用

或者javascripts native
location.hash
类似

location.hash = '#' + anchorid;
根本不需要jQuery

简单得多:

var element_to_scroll_to = document.getElementById('anchorName2');
// Or:
var element_to_scroll_to = document.querySelectorAll('.my-element-class')[0];
// Or:
var element_to_scroll_to = $('.my-element-class')[0];
// Basically `element_to_scroll_to` just have to be a reference
// to any DOM element present on the page
// Then:
element_to_scroll_to.scrollIntoView();

jAndy提出了一个很好的解决方案,但在firefox中,平滑滚动似乎存在一些问题

这样写在Firefox中也同样有效

(function($) {
    $(document).ready(function() {
         $('html, body').animate({
           'scrollTop':   $('#anchorName2').offset().top
         }, 2000);
    });
})(jQuery);

我知道这是一个非常古老的问题,但我在中找到了一个简单易用的jQuery解决方案。我现在用的就是这个

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

大多数答案都过于复杂

如果您只想跳到目标元素,则不需要JavaScript:

# the link:
<a href="#target">Click here to jump.</a>

# target element:
<div id="target">Any kind of element.</div>
#链接:
#目标要素:
任何一种元素。

如果您想动态地滚动到目标,请参考@Shahil的答案。

CSS技巧的解决方案在jQuery 2.2.0中不再有效。它将抛出一个选择器错误:

JavaScript运行时错误:语法错误,无法识别的表达式:a[href*=#]:not([href=#])

我通过改变选择器来修复它。完整片段如下所示:

$(函数(){
$([a[href*='#']:非([href='#'])),单击(函数(){
if(location.pathname.replace(/^\/,'')==this.pathname.replace(/^\/,'')和&location.hostname==this.hostname){
var target=$(this.hash);
target=target.length?target:$('[name='+this.hash.slice(1)+']');
if(目标长度){
$('html,body')。设置动画({
scrollTop:target.offset().top
}, 1000);
返回false;
}
}
});
});

一个没有JQuery的纯javascript解决方案。在Chrome上测试,即未在IOS上测试

function ScrollTo(name) {
  ScrollToResolver(document.getElementById(name));
}

function ScrollToResolver(elem) {
  var jump = parseInt(elem.getBoundingClientRect().top * .2);
  document.body.scrollTop += jump;
  document.documentElement.scrollTop += jump;
  if (!elem.lastjump || elem.lastjump > Math.abs(jump)) {
    elem.lastjump = Math.abs(jump);
    setTimeout(function() { ScrollToResolver(elem);}, "100");
  } else {
    elem.lastjump = null;
  }
}

演示:

这是一个工作脚本,可以将页面滚动到锚点。 要进行设置,只需为锚点链接提供一个与要滚动到的锚点的name属性匹配的id

<script>
jQuery(document).ready(function ($){ 
 $('a').click(function (){ 
  var id = $(this).attr('id');
  console.log(id);
  if ( id == 'cet' || id == 'protein' ) {
   $('html, body').animate({ scrollTop: $('[name="' + id + '"]').offset().top}, 'slow'); 
  }
 }); 
});
</script>

jQuery(文档).ready(函数($){
$('a')。单击(函数(){
var id=$(this.attr('id');
console.log(id);
如果(id='cet'| | id=='protein'){
$('html,body').animate({scrollTop:$('[name=“'+id+'''“]).offset().top},'slow');
}
}); 
});

在2018年,像这样简单的事情不需要jQuery。内置方法支持“
行为”
”属性以平滑滚动到页面上的任何元素。您甚至可以使用散列更新浏览器URL,使其成为书签

从中,以下是一种自动向页面上的所有锚定链接添加平滑滚动的本机方法:

let anchorlinks = document.querySelectorAll('a[href^="#"]')
 
for (let item of anchorlinks) { // relitere 
    item.addEventListener('click', (e)=> {
        let hashval = item.getAttribute('href')
        let target = document.querySelector(hashval)
        target.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        })
        history.pushState(null, null, hashval)
        e.preventDefault()
    })
}
这项工作:

$('.scroll').on("click", function(e) {

  e.preventDefault();

  var dest = $(this).attr("href");

  $("html, body").animate({

    'scrollTop':   $(dest).offset().top

  }, 2000);

});

只需将类“滚动”添加到任何要设置动画的链接中

jQuery(“a[href^='#'])。单击(函数(){
jQuery('html,body')。动画({
scrollTop:jQuery(jQuery(this).attr('href')).offset().top
}, 1000);
返回false;
});2018-2020纯js:
有一种非常方便的方法可以滚动到元素:
但据我所知,他并没有像下面这些选项那样得到很好的支持


如果有必要使元件位于顶部:


如果希望图元位于中心,请执行以下操作:


支持:

他们写道,
scroll
scrollTo
的方法相同,但在
scrollTo
中支持效果更好


vue2解决方案。。。添加简单数据属性以强制更新

  const app = new Vue({ 
  ... 

  , updated: function() {
           this.$nextTick(function() {
           var uri = window.location.href
           var anchor = ( uri.indexOf('#') === -1 ) ? '' : uri.split('#')[1]
           if ( String(anchor).length > 0 && this.updater === 'page_load' ) {
              this.updater = "" // only on page-load !
              location.href = "#"+String(anchor)
           }
         })
        }
     });
     app.updater = "page_load"

 /* smooth scrolling in css - works in html5 only */
 html, body {
     scroll-behavior: smooth;
 }
平稳地滚动到正确的位置 获取正确的
y
坐标并使用
窗口。滚动到({top:y,behavior:'smooth'})

const id = 'anchorName2';
const yourElement = document.getElementById(id);
const y = yourElement.getBoundingClientRect().top + window.pageYOffset;

window.scrollTo({top: y, behavior: 'smooth'});

要使浏览器将页面滚动到给定的定位点,最简单的方法是键入style.css*{scroll behavior:smooth;} 在html导航中使用#name of部分

*{滚动行为:平滑;}
主页
其他章节

其他章节

其他章节

其他章节

其他章节

其他章节

其他章节

其他章节

其他章节

其他章节

其他章节

其他章节

其他章节

它将向下滚动到此部分


至于创建一个选择器来查找
,请使用
$('#'+hash+',a[name='+hash+'])
或稍微优化的
$(document.getElementById(hash)|'a[name='+hash+'])
,它将首先按id搜索元素,只有在找不到a的情况下才搜索a。@gnarf-没有任何必要优化jQuery中的“#”选择器-它们已经为您进行了优化。很容易看出您是否读过jQuery源代码。@CodeJoust-我是jQuery团队的成员,我读过很多次,是的,
$(“#选择器”)
经过了优化,但是
$(“#选择器,一个[name='selector'])
不会很快进行同样的优化。我想我2.5年前的评论听起来有点奇怪。“优化”是避免在找到id时进行
a[name='selector']
搜索,而不是优化对id的搜索。我在这种方法上有些运气:大约$(“[data hash]”)。单击(function(){var data=$(this.attr(“data hash”);$(document.body)。动画({'scrollTop':$(“#”+data.offset().top},500););有时这是不准确的。。。当页面有带有惰性加载的动态部分时,我起初认为Mandx是拖拉的,然后我尝试了这个方法,它成功了。我不明白我以前怎么没见过这种方法。此外,这似乎将是一个错误
let anchorlinks = document.querySelectorAll('a[href^="#"]')
 
for (let item of anchorlinks) { // relitere 
    item.addEventListener('click', (e)=> {
        let hashval = item.getAttribute('href')
        let target = document.querySelector(hashval)
        target.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        })
        history.pushState(null, null, hashval)
        e.preventDefault()
    })
}
$('.scroll').on("click", function(e) {

  e.preventDefault();

  var dest = $(this).attr("href");

  $("html, body").animate({

    'scrollTop':   $(dest).offset().top

  }, 2000);

});
el.scrollIntoView({
  behavior: 'smooth', // smooth scroll
  block: 'start' // the upper border of the element will be aligned at the top of the visible part of the window of the scrollable area.
})
const element = document.querySelector('#element')
const topPos = element.getBoundingClientRect().top + window.pageYOffset

window.scrollTo({
  top: topPos, // scroll so that the element is at the top of the view
  behavior: 'smooth' // smooth scroll
})
const element = document.querySelector('#element')
const rect = element.getBoundingClientRect() // get rects(width, height, top, etc)
const viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);

window.scroll({
  top: rect.top + rect.height / 2 - viewHeight / 2,
  behavior: 'smooth' // smooth scroll
});
  const app = new Vue({ 
  ... 

  , updated: function() {
           this.$nextTick(function() {
           var uri = window.location.href
           var anchor = ( uri.indexOf('#') === -1 ) ? '' : uri.split('#')[1]
           if ( String(anchor).length > 0 && this.updater === 'page_load' ) {
              this.updater = "" // only on page-load !
              location.href = "#"+String(anchor)
           }
         })
        }
     });
     app.updater = "page_load"

 /* smooth scrolling in css - works in html5 only */
 html, body {
     scroll-behavior: smooth;
 }
const id = 'anchorName2';
const yourElement = document.getElementById(id);
const y = yourElement.getBoundingClientRect().top + window.pageYOffset;

window.scrollTo({top: y, behavior: 'smooth'});