簡體   English   中英

我怎樣才能使用超過 2 個部分的 JavaScript 代碼?

[英]How can I usa this JavaScript code with more than 2 sections?

我是 javascript 和 Html 的新手,我創建了兩個滾動按鈕到 go 從 section1 到 section2。 如果我需要有兩個以上的部分,我該怎么辦?

function f1() {
        var elmnt1 = document.getElementById("sez1");
        elmnt1.scrollIntoView();
    }
    function f2() {
        var elmnt2 = document.getElementById("sez2");
        elmnt2.scrollIntoView();
    }

最好的方法是為任何解決方案創建一個模式,使其成為通用解決方案。

  1. 使用您喜歡的屬性標記您的部分,例如:scroll-to-id="1",您的部分現在看起來像<div scroll-to-id="1"></div><div scroll-to-id="2"></div><div scroll-to-id="3"></div><div scroll-to-id="4"></div>
  2. 現在制作一個 function ,它將數字作為輸入並滾動到所需的部分。 要獲取所有目標部分,我們可以調用 function document.querySelectorAll('[scroll-to-id]')以獲取具有屬性 scroll-to-id 的所有元素。
  3. 然后找到具有所需scroll-to-id的元素到 go 到並滾動到該元素。

完整解決方案如下:

 function scrollToSection(sectionId) { const sections = document.querySelectorAll('[scroll-to-id]'); for(let section of sections) { if(section.getAttribute('scroll-to-id') == sectionId) { section.scrollIntoView(); // scrollIntoView doesnot have the best browser supports. It is better to calculate the position of the section and do a scrollTo() or scrollBy() } } }
 button { margin-bottom: 20px; } div { padding-top: 80px; padding-bottom: 80px; border: 1px solid #cecece; }
 <button onclick="scrollToSection(1)">Scroll To 1</button> <button onclick="scrollToSection(2)">Scroll To 2</button> <button onclick="scrollToSection(3)">Scroll To 3</button> <button onclick="scrollToSection(4)">Scroll To 4</button> <div scroll-to-id="1">Hello 1</div> <div scroll-to-id="2">Hello 2</div> <div scroll-to-id="3">Hello 3</div> <div scroll-to-id="4">Hello 4</div>

將元素作為參數傳遞給您的 function

function scroll(el){
  el.scrollIntoView()
}

歡迎來到 Stackoverflow @Francy3k!

只需更新您現有的 function 以接受您要滾動到的部分的 ID:

 .buttons { position:fixed; top:0; left:0; width:100%; background:white; padding:10px 0; text-align:center } #sez1 { height:300px; background:green; vertical-align:middle } #sez2 { height:300px; background:red; vertical-align:middle } #sez3 { height:300px; background:blue; vertical-align:middle }
 <div class="buttons"> <button onclick="scrollToSection(1)">Go to SEZ1</button> <button onclick="scrollToSection(2)">Go to SEZ2</button> <button onclick="scrollToSection(3)">Go to SEZ3</button> </div> <div id="sez1"> </div> <div id="sez2"> </div> <div id="sez3"> </div> <script> function scrollToSection(index) { const section = document.getElementById("sez" + index); section.scrollIntoView(); } </script>

如果部分 ID 遵循相同的約定,您應該能夠使用此模式。

暫無
暫無

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

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