簡體   English   中英

使用固定菜單調整錨點到其他頁面

[英]Adjust anchor to other pages with a fixed menu

我正在一個頂部固定菜單的網站上工作。 在主頁上,我的標簽應該錨定到我網站上其他頁面的 id。 這些 id 的錨點工作正常,但是,其內容的頂部保留在固定菜單的后面。

我嘗試通過使用 JavaScript 動畫方法並添加菜單的高度值來解決它。 當錨點的命運 id 來自同一頁面時,這很有效。 但在我的情況下它不起作用,因為我想 go 到網站另一個頁面中的 id。

我的HTML

<a href="http://localhost/meu_site/psicologia#psicoterapia" class="psi-block-item"></a>

我的JavaScript

<script src="http://localhost/meu_site/js/jquery-3.4.1.min.js"></script>

$('.psi-block-item').click(function() {
    var target = $(this).attr("href")
    $("html, body").animate({ scrollTop: $(target).offset().top-100 }, 100)
})

顯然,當從主頁跳轉到另一個頁面時,它似乎忽略了我最后的js命令而只是按照href,將部分內容保留在固定菜單后面。

我已經看到有人建議使用偽 css 元素並隱藏它們以使其工作,但我正在尋找一個干凈且更專業的解決方案,僅使用 html 和 javascript。

謝謝大家。

頁面很可能在執行代碼之前被重新加載。 因此,我建議您在每個尋找 hash 然后執行 animation 的頁面中包含一個 window onload 事件偵聽器。

編輯:請參閱@nengak-dakup 的答案。 他的回答看起來很不錯。 實現看起來像這樣。

索引.html

<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Home</title>
</head>
<body>
    <header>
        <a href="page1.html#anchor1">Link to Page1 - Anchor 1</a>
        <a href="page1.html#anchor2">Link to Page1 - Anchor 2</a>
        <a href="page1.html#anchor3">Link to Page1 - Anchor 3</a>
    </header>
</body>

和page1.html

<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Page1</title>
    <style type="text/css">
        header {
            position: fixed;
            top: 0px;
            left: 0px;
            width: 100%;
            height: 100px;
            background-color: grey;
            z-index: 5;
        }
        .box {
            position: relative;
            top: 100px;
            width: 100%;
            height: 800px;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
    <script type="text/javascript">
        $(document).load(function() {
            var target = this.location.href;
            $("html, body").animate({ scrollTop: $(target).offset().top-100 }, 100);
        })
    </script>
</head>
<body>
    <header>
        <a href="index.html">Back</a>
    </header>
    <div id="anchor1" class="box" style="background-color: blue"></div>
    <div id="anchor2" class="box" style="background-color: green"></div>
    <div id="anchor3" class="box" style="background-color: red"></div>
</body>

$(document).load(function() {
    var target = this.location.href;
    $("html, body").animate({ scrollTop: $(target).offset().top-100 }, 100);
})

我不確定,但這應該是解決它的邏輯......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM