Home > Web Front-end > JS Tutorial > body text

Usage of location.hash

DDD
Release: 2023-06-25 16:58:29
Original
2001 people have browsed it

location.hash is a property in JavaScript that is used to get or set the anchor part of the URL. It can be used to get or set the anchor part of the URL.

Usage of location.hash

location.hash is a property in JavaScript that is used to get or set the anchor part in the URL (that is, the # symbol and the part after it in the URL ).

Get the anchor part in the URL:

You can use location.hash to get the anchor part in the URL. What is returned is a string, including the # symbol and the following part. For example, if the URL is "https://www.example.com/#section1", then location.hash will return "#section1".

Sample code:

javascript
console.log(location.hash);//输出"#section1"
Copy after login

Set the anchor part in the URL:

You can use location.hash to set the anchor part in the URL. It should be noted that when location.hash is set, the anchor part of the URL will be automatically replaced with the new value, and will cause the page to scroll to the corresponding anchor position.

Sample code:

javascript
location.hash="#section2";
Copy after login

Notes:

- The obtained location.hash always includes the # symbol, which can be removed through string processing methods.

- The value of location.hash is readable and writable and can be used to implement dynamic operations on URL anchors.

- When setting location.hash, if the new value is the same as the current anchor value, the page will not scroll. Only different values ​​will cause the page to scroll.

The above is the detailed content of Usage of location.hash. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!