簡體   English   中英

如何在 Bootstrap 5 中以編程方式打開 offcanvas?

[英]How to open offcanvas programmatically in Bootstrap 5?

我的網頁中有一個底部的 offcanvas,我會通過單擊卡片打開它,通過嘗試設置所需的屬性或使用文檔中的代碼它不起作用,因為 offcanvas 僅顯示背景並立即將其關閉。

這是我嘗試過的:

 const products = document.getElementsByClassName("card product"); var productClick = function (event) { event.preventDefault() var myOffcanvas = document.getElementById('offcanvasBottom') var bsOffcanvas = new bootstrap.Offcanvas(myOffcanvas) bsOffcanvas.show(); }; Array.from(products).forEach(function (element) { element.addEventListener("click", productClick); });
 <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script> <div class="card product" style="width: 18rem"> <div class="card-body text-center"> <h2 class="card-title fw-bolder">TEST</h2> <p class="card-text fw-bolder">TEST</p> </div> </div> <div class="offcanvas offcanvas-bottom" tabindex="-1" id="offcanvasBottom" > <div class="offcanvas-header"> <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close" ></button> </div> <div class="offcanvas-body"> BODY </div> </div>

問題是卡片點擊事件正在傳播到內部元素。 而是使用event.stopPropagation() ...

 const products = document.getElementsByClassName("product"); var myOffcanvas = document.getElementById('offcanvasBottom') var productClick = function (event) { //event.preventDefault() event.stopPropagation() var bsOffcanvas = new bootstrap.Offcanvas(myOffcanvas) bsOffcanvas.show() } Array.from(products).forEach(function (element) { element.addEventListener("click", productClick); })
 <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script> <div class="card product" style="width: 18rem"> <div class="card-body text-center"> <h2 class="card-title fw-bolder">TEST</h2> <p class="card-text fw-bolder">TEST</p> </div> </div> <div class="offcanvas offcanvas-bottom" tabindex="-1" id="offcanvasBottom" > <div class="offcanvas-header"> <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close" ></button> </div> <div class="offcanvas-body"> BODY </div> </div>

暫無
暫無

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

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