你可以使用JavaScript的Intersection Observer来判断某个div是否可见,然后根据判断结果来修改包含data-md-component="header"属性的div的class。

首先,你需要给要判断可见性的div添加一个id,比如targetDiv:

<div id="targetDiv"></div>

然后,你可以使用以下JavaScript代码来监听targetDiv的可见性变化:

// 创建一个新的 Intersection Observer 对象
const observer = new IntersectionObserver(entries => {
  // entries 是一个包含所有被观察元素的可见性信息的数组
  entries.forEach(entry => {
    // 判断被观察的元素是否可见
    if (entry.isIntersecting) {
      // 如果可见,则执行相应的操作,这里是修改包含 data-md-component="header" 属性的 div 的 class
      const headerDiv = document.querySelector('[data-md-component="header"]');
      headerDiv.classList.add('new-class');
    } else {
      // 如果不可见,则执行相应的操作,这里是移除新添加的 class
      const headerDiv = document.querySelector('[data-md-component="header"]');
      headerDiv.classList.remove('new-class');
    }
  });
});

// 开始观察 targetDiv 的可见性
const targetDiv = document.getElementById('targetDiv');
observer.observe(targetDiv);

上述代码创建了一个新的Intersection Observer对象,并使用observe()方法开始观察targetDiv的可见性。当targetDiv的可见性发生变化时,Intersection Observer会调用回调函数,回调函数中根据可见性的变化来执行相应的操作。

在回调函数中,我们首先通过document.querySelector('[data-md-component="header"]')获取包含data-md-component="header"属性的div元素,然后使用classList对象的add()方法和remove()方法来添加或移除新的class。

你可以根据自己的需求修改相应的class名称和操作。

JavaScript判断某个div如果网页往下滑导致屏幕不会显示此div则执行把包含data-md-component=header 属性的div的class修改

原文地址: https://www.cveoy.top/t/topic/i2o2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录