检测您在 JavaScript 上的哪个页面?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16133491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:22:56  来源:igfitidea点击:

Detect what page you are on JavaScript?

javascripthtml

提问by Callum

Is there any way to detect what page you are on in JavaScript?

有什么方法可以检测您在 JavaScript 中的页面吗?

Why I want to know is so that i can detect what page i am on, and then set the style of an element accordingly.

为什么我想知道是这样我就可以检测到我在哪个页面上,然后相应地设置元素的样式。

采纳答案by m.edmondson

document.URLwill get you the URL of the current page.

document.URL将为您提供当前页面的 URL。

To check for a specific page you would use:

要检查特定页面,您将使用:

if ( document.URL.includes("homepage.aspx") ) {
    //Code here
}

回答by Roman Nazarkin

Get url of page are you on

获取页面的 url 你在

location.href

Or

或者

document.URL

Set style to element by id:

通过 id 将样式设置为元素:

document.getElementById('mydiv').style.border = '1px solid black';