我正在尝试创建一个包含一些隐藏div的网站,如果URL在显示ID为SOMETHING({{1的ID)的潜水中显示#SOMETHING(http://website.com/#SOMETHING),该怎么做? }})在JavaScript中,可以吗? (我想做的是,如果URL具有#example,则某些脚本将从ID为#(示例)的div中删除hiddenfile类)
代码:
<div id="SOMETHING">...</div>
答案 0 :(得分:1)
您可以使用window.location.hash
:
selector = document.querySelector(window.location.hash)
selector.style.display = 'block'
selector.style.opacity = 1
selector.style.visibility = 'visible'
答案 1 :(得分:0)
@BhojendraRauniyar的答案有效,但仅适用于目前的情况-仅适用于从另一个页面登陆到您页面上的链接的情况。
如果您希望在单击页面内的锚链接时具有相同的行为,则需要实现onhashchange
处理程序并处理隐藏的显示元素。
请注意,所有特殊元素的类名都已更改。
function checkSomething(event) {
[...document.querySelectorAll(".SOMETHING")].forEach( (div) =>
// hide or show all "SOMETHING" elements as necessary
div.classList[(div.id == window.location.hash.substring(1)) ? "remove" : "add"]("hiddenfile")
)
}
function init() {
window.onhashchange = checkSomething;
// need to check if an external link was to an anchor
checkSomething();
}
document.addEventListener("DOMContentLoaded", init)
.hiddenfile {
opacity: 0;
visibility: hidden;
display: none;
}
<body>
<div>
<a href="#SOMETHING">Test for 1st div</a>
<a href="#SOMETHING2">Test for 2nd div</a>
<a href="#SOMETHING3">Test for 3rd div</a></div>
<div id="SOMETHING" class="SOMETHING hiddenfile" name="SOMETHING">SOMETHING</div>
<div id="SOMETHING2" class="SOMETHING hiddenfile" name="SOMETHING2">SOMETHING2</div>
<div id="SOMETHING3" class="SOMETHING hiddenfile" name="SOMETHING3">SOMETHING3</div>
</body>
</style>