如何使用 JavaScript 建立上一個和下一個按鈕,並在結束位置停用它們?
我們可以使用原生 JavaScript 建立上一個和下一個按鈕,並在它們到達末端位置時使其無法使用(或停用)。JavaScript 是一種強大的瀏覽器級語言,我們可以輕鬆地使用它來控制和操作 DOM 元素。在這裡,我們將建立 2 個按鈕,並根據點選哪個按鈕來更改 HTML 元素的內容。
示例 1
在這個示例中,我們將建立一個“遞增”和一個“遞減”按鈕,當點選它們時,分別將 HTML 元素的內容值遞增和遞減 1。我們還將在它們到達極限位置時停用按鈕,對於遞增按鈕,極限位置為 5,對於遞減按鈕,極限位置為 0。
<html lang="en"> <head> <title>How to create previous and next button and non-working on end position using JavaScript?</title> </head> <body> <h3>How to create previous and next button and non-working on end position using JavaScript?</h3> <p>3</p> <div> <button class="inc">Increment</button> <button class="dec">Decrement</button> </div> <script> const inc = document.getElementsByClassName('inc')[0] const dec = document.getElementsByClassName('dec')[0] const content = document.getElementsByTagName('p')[0] let i = 3; inc.addEventListener('click', () => { if (i === 5) return; i++; content.textContent = i; }) dec.addEventListener('click', () => { if (i === 0) return; i--; content.textContent = i; }) </script> </body> </html>
示例 2
在這個示例中,讓我們實現上述方法,但不是顯示數字的增減,而是顯示“絕對”定位元素的左對齊方式的增減。
<html lang="en"> <head> <title>How to create previous and next button and non-working on end position using JavaScript?</title> <style> body { position: relative; } .dot { background-color: black; height: 5px; width: 5px; border-radius: 50%; position: absolute; } .inc, .dec { margin-top: 20px; } </style> </head> <body> <h3>How to create previous and next button and non-working on end position using JavaScript?</h3> <div class="dot"></div> <div> <button class="inc">Increment</button> <button class="dec">Decrement</button> </div> <script> const inc = document.getElementsByClassName('inc')[0] const dec = document.getElementsByClassName('dec')[0] const dot = document.getElementsByClassName('dot')[0] let i = 0; inc.addEventListener('click', () => { if (i === 10) return; i += 2; dot.style.left = `${i}%` }) dec.addEventListener('click', () => { if (i === 0) return; i -= 2; dot.style.left = `${i}%` }) </script> </body> </html>
結論
在本文中,我們學習瞭如何使用 Bootstrap 4 在 Web 應用程式中建立分頁佈局,並使用了兩個不同的示例。在第一個示例中,我們使用數字顯示了遞增和遞減,在第二個示例中,我們使用“絕對”定位元素的左值顯示了值的遞增和遞減。
廣告