你們中有人遇到過類似的問題嗎?我在網站的一個頁面上有鏈接,這些鏈接重定向到第二頁,在那里我有一個選單,每次顯示一個選單選項。默認情況下,當我打開第二頁時,第一個選項是可見的。但是,當我點擊這樣的鏈接,顯示隱藏的div并向下滾動到div內容的特定部分時,我怎樣才能得到一個結果呢?
第一頁上的鏈接。它應該加載選項4并向下滾動到錨點#extrainformation。
< div class="linktosecondpage" onclick="window。 open('http://localhost/mypage/secondpage#extrainformation', '_self');">
</div>
第二頁的選單看起來如何?
https://jsfiddle.net/wmr03zno/3/
我曾考慮為每個鏈接寫出一個函式,當點擊鏈接時激活,重定向到第二頁,顯示該頁的隱藏選項,洗掉并添加類到h4,并向下滾動到所需的錨(#extrainformation)。這就是我現在的想法。只是想知道是否有一個更簡單的解決方法來解決這種問題。
uj5u.com熱心網友回復:
這涉及到一點JavaScript的問題。在加載時,你可以尋找Location: hash(你的URL中已經有了這個)。對頁面做一些事情。在我的例子中,我創建了獲得哈希值的元素,然后使用Element.scrollIntoView() 來導航到該元素。
。window。 location.hash = 'test'; // 用于測驗。這已經在URL中設定好了。。
document.addEventListener('DOMContentLoaded', e => /span>{
//span>找到哈希值。
let hash = window.location.hash。 slice(1); // slice: remove the '#'。
//加入一個新的元素(或使其可見等)。
document.querySelector('main')。 innerHTML = `<h2 id="${hash}">${hash}</h2> `。
//滾動到錨點。
document.querySelector(`#${hash}`) 。 scrollIntoView()。
});
span class="hljs-selector-tag">main {
height: 2000px;
position: relative;
}
h2#test {
position: absolute;
top: 1000px;
}
< main><main> /span>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
我的想法是,從鏈接中讀取哈希值,如果具有給定哈希值的元素存在,則滾動到它。
在第一頁,你將有一個像這樣的鏈接:
在第一頁,你將有一個像這樣的鏈接。
<ahref="https://example. com/subpage/#anchor">anchor< /a>
而在第二頁,你將需要這樣的東西。
當頁面準備好時,狀態將被改變為interactive檢查鏈接是否包含錨(location.hash),如果包含則嘗試scrollToElement()函式。
在這個函式中,檢查是否存在具有給定錨的元素,如果它存在,則顯示它并滾動到它。
const scrollToElement = (id) => {
const element = document.querySelector(id)。
if (element !== null) {
element.classList.remove('hidden')。
element.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"})。)
}
};
document.onreadystatechange = () => {
if (document.readyState == 'interactive') {
if (location.hash !== ' ') {
scrollToElement(location.hash)。
}
};
.hidden {
display: none;
}
<div style="height: 2000px"></div>>
<div id="anchor" class="hidden"> anchor</div>/span>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
我一直在思考并嘗試一些東西。我嘗試了上面由@ciekals11和@chrwahl回答的解決方案,但無法讓這些解決方案發揮作用。可能是因為我對js/Jquery太業余了吧。
無論如何,我的解決方案看起來是這樣的。
$(document).ready(function(>/span>) {
if (
window.location.href == "http://localhost/mypage/secondpage#extrainformation".
) {
$(".tabs h4").removeClass("tab-current") 。
$(".tabs ul li:nth-child(4) h4").addClass("tab-current")。
$("#section1").fadeOut()。
$("#section4").fadeIn()。
$([document.documentElement, document. body]).animate({
scrollTop: $("#extrainformation"/span>).offset().top
}, 1000)。)
return false。
}
});
這可能不是最好的答案,但它是有效的。我們歡迎任何其他建議和解決方案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/321662.html
標籤:
