简体   繁体   English

我如何在页面加载时滚动到特定的 div

[英]How can i do scroll to specific div on page load

I have this html codes:我有这个 html 代码:

<span name="value1"></span>
<span name="value2"></span>

I'm trying to make the page scroll to these sections every time the page's URL with the span loads.每次页面的 URL 加载跨度时,我都试图让页面滚动到这些部分。

Example: htttp://site.com/index.html#value1

If value1 is selected, there is a scroll when the page is opened.如果选择value1 ,则打开页面时有滚动。

I'm trying this code:我正在尝试这段代码:

$(document).ready(function() {  
        var target = $(this.hash);  
        if (target.length == 0) target = $('[name="' + this.hash.substr(1) + '"]');  
        if (target.length == 0) target = $('html');  
        $('html, body').animate({ scrollTop: target.offset().top }, 700);  
        return false;  
});

I can do this with id but I want to do it with name attr.我可以用id做到这一点,但我想用名字 attr 做到这一点。

May I kindly suggest to consider a solution without JavaScript?我可以建议考虑没有 JavaScript 的解决方案吗?

<a name="value1"></a><span name="value1"></span>

This will use the browser's default behavior to go to the respective section upon loading the page.这将在加载页面时使用浏览器的默认行为 go 到相应的部分。


Should the identification of the element be the issue, you may try traditional JS:如果元素的识别是问题,您可以尝试传统的 JS:

if (target.length == 0) {
    target = document.getElementsByName(window.location.hash.substr(1))[0];
}

Your JavaScript code looks like it should work for both id and name attributes, and since it works for ids, I think maybe the problem is one of two possible issues in your HTML:您的 JavaScript 代码看起来应该适用于idname属性,并且由于它适用于 id,我认为问题可能是您的 HTML 中的两个可能问题之一:

1. When you're trying to scroll to an element by name , do you also have an element with that id on the page? 1. 当您尝试按name滚动到某个元素时,页面上是否还有一个具有该id的元素?

As you can see from these lines in your code:从代码中的这些行可以看出:

var target = $(this.hash);  
if (target.length == 0) target = $('[name="' + this.hash.substr(1) + '"]'); 

The script will only look for an element with name={hash} if an element with id={hash} is not found.如果未找到具有id={hash}的元素,该脚本将仅查找具有name={hash}的元素。

2. Your tags are invalid HTML 2.您的标签无效 HTML

I don't think this technically should prevent the script from working the way you want, but it's probably useful to know anyway.我认为这在技术上不应该阻止脚本按您想要的方式工作,但无论如何知道它可能很有用。 Only certain elements are supposed to have a name attribute, as you can see from this other SO question .正如您从其他SO question中看到的那样,只有某些元素应该具有name属性。

I believe what you want here is <a name="value..."> , using the Anchor tag for one of its original intended uses .我相信您在这里想要的是<a name="value..."> ,将 Anchor 标签用于其 最初的预期用途之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM