代码之家  ›  专栏  ›  技术社区  ›  Ben

togglePopover()不打开但不关闭本机HTML popover

  •  0
  • Ben  · 技术社区  · 4 周前

    我正在尝试使用HTML的原生 popover 。我尝试过使用以下JavaScript来打开/关闭popover。

    HTML

    <div>
      <button onclick="handlePopover(event, 'popover-1')">+</button>
      <aside id="popover-1" popover="">
        <p>My Test</p>
      </aside>
    </div>
    

    JavaScript

    function handlePopover(event, id) {
      // Identify the first popover element with the given id
      const popover = document.getElementById(id)
    
      // Exit early if no matching popover was found
      if (!popover) return
    
      // Get the coordinates of the clicked button
      let rect = event.target.getBoundingClientRect()
    
      // Modify the coordinates of the popover
      popover.style.left = rect.left + 10 + "px"
      popover.style.top = rect.top + 10 + "px"
    
      // Toggle the display state
      popover.togglePopover()
    }
    

    popover切换正确,位置正确。但是,当我第二次(或第三次或第四次)单击按钮时,它不会关闭。但是,请注意,如果我在弹出区域之外而不是在按钮顶部单击,则弹出框确实会消失。

    第二次单击按钮时,如何隐藏弹出窗口?

    1 回复  |  直到 4 周前
        1
  •  3
  •   underscore    4 周前

    Demo

    没有自定义事件处理程序

    你可以很容易地使用 popovertarget 属性

    <div>
      <button popovertarget="popover-1">+</button>
      <aside id="popover-1" popover>
        <p>My Test</p>
      </aside>
    </div>
    

    使用自定义事件处理程序

    使用手动弹出状态

    如果要为此使用自定义事件,请使用 popover="manual"

     <aside id="popover-1" popover="manual">
        <p>My Test</p>
      </aside>
    
        2
  •  0
  •   Kiki    4 周前

    你也可以这样做:

    a) 给你的按钮一个id

     <button id="popOverId" onclick="handlePopover(event, 'popover-1')">+</button>
    

    b) 切换pop单击按钮时切换popOver

        let toggle = true;
        
        function handlePopover(event, id) {
            // Identify the first popover element with the given id
            const popover = document.getElementById(id)
        
            // Exit early if no matching popover was found
            if (!popover) return
        
            // Get the coordinates of the clicked button
            let rect = event.target.getBoundingClientRect()
        
            // Modify the coordinates of the popover
            popover.style.left = rect.left + 10 + "px"
            popover.style.top = rect.top + 10 + "px"
        
            // Toggle the display state
            popover.togglePopover(toggle);
        
        }
        
        
        document.addEventListener("click", (evt) => {
        
            if (evt.target.id !== "popOverId") {
                toggle = true;
            } else {
                toggle = !toggle;
            }
        
        });
    

    underline的解决方案更简洁明了,所以如果它能满足您的需求,那就选它吧。