您是否可以使用<a name="#page"> in javascript?

时间:2017-08-19 01:15:49

标签: javascript html scroll

I'm trying to code a site to host a comic, and each page is reached by scrolling with < a name=#page(number) > in html. So the button to go to the next page would be:

<a href = #page1></a>

Then, later in the code would be:

<a name = #page1></a>

Which would make the button scroll to there. But I'd also like to implement being able to use arrow keys, which would require knowing what #page you are on, and use it to set a variable as the next page number, to use on my arrow key checker, which is now in a javascript file:

case 39:
window.location = "willow.html#page" + nextPage;  
break;

I've tried

if (location.href === "example.com/index.html#page1") {
    var nextPage = 2;
}

And it doesn't work. Is there some way to check what < a name > you are at in javascript? Thanks in advance!

1 个答案:

答案 0 :(得分:3)

您可以使用location.hash来检查使用了"#anchor"(可能是name=还是id=)。它不会反映滚动,但会反映地址栏和您单击的任何页内链接。

if (location.hash === "#page1") {
    var nextPage = 2;
}