介绍几个html 原生的一些API

介绍几个html 原生的一些API

IntersectionObserver

当某个DOM元素出现在视口的时候,我们希望执行一些行为.这个时候我们就可以使用这个API.例如我们在实现无限滚动这样的组件的时候,我们会在滚动容器的底部放置一个元素,但这个元素出现在视口的时候,我们希望加载更多的内容,这个时候,我们就可以使用这个API

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inflite Scroll Example</title>
    <link rel="stylesheet" href="styles.css">
    <script src="inflite-scroll.js" defer></script>
</head>
<body>
    <div id="container">

    </div>
    <div id="anchor"></div>
    
</body>
</html>
const container =   document.querySelector('#container');
const anchor =  document.querySelector('#anchor');
const items = new Array(100000).fill(0).map((_, i) => `item ${i + 1}`);
const step = 100;
let show = 0;

const showMore=()=>{
    const start = show;
    show += step;
    container.insertAdjacentHTML('beforeend',items.slice(start, show).map(item => `<div class="item">${item}</div>`).join(''));    
}

const initialize = ()=>{
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                showMore();
            }
        });
    }); 
    observer.observe(anchor);
}

initialize();

popover

对于弹框,这个是一个老生常谈的问题,传统的做法是在body 上插入一个DOM,然后通过js 的align 算法来实现对某个元素相对于锚点元素的定位,并支持位置反转.这个也是上古的神器了.这个是费事费力,而且还有性能问题.现在浏览器原生就开始支持这个行为了,这个不香吗? 当然前提是(Edge>128, chromium>128)

  • popover这个属性,拥有这个属性的就是被弹框的元素,它有一个showPopover(param?:{source:HTMLElement})可以打开弹框.这个里面的source就是锚点元素. 同时它还有css rule来定位,例如css-position,例如其中的position-area规则来定位元素,position-try-fallbacks来设置备用定位信息.position-anchor来设置锚点元素,以及anchor-name: --some-anchor-name(这个是作用于锚点元素上的),来定义锚点元素
  • 我们也可以通过html的属性来建立锚点元素与弹框元素间的关系,例如
<button popovertarget="popoverContent1" class="trigger">Click me</button>
       <div id="popoverContent1" class="popover" popover>
           <h3>Popover Title</h3>
           <p>This is the content of the popover.</p>
           <button popovertarget="popoverContent1" popovertargetaction="hide">Close</button>
       </div>
  • 我们也可以在弹框元素的showPopover(param?:{source:HTMLElement})的时候传递参数,指定锚点元素.
posted @ 2025-07-13 11:44  kongshu  阅读(7)  评论(0)    收藏  举报