滚动EventListener停止工作



问题是当我启用EventListener宽度时,滚动eventListener停止工作。

var header = document.getElementById("header");
var nav = document.getElemantById("ulArea");
var HaLogo = document.getElementById("logo");
var yPosition = window.scrollTop();
window.addEventListener("scroll" , yScroll);
function yScroll () {
    if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
        header.style.height = "90px";
        logo.style.float = "left";
        logo.style.height = "90px";
        logo.style.width = "90px";
        logo.style.margin = "0px 0px 10px 30px";
        ulArea.style.margin = "0px 0px 0px auto";
        ulArea.style.float = "none";
    } else {
        header.style.height = "220px";
        logo.style.background = "transparent";
        logo.style.float = "none";
        logo.style.height = "150px";
        logo.style.width = "150px";
        logo.style.margin = "0 auto";
        ulArea.style.margin = "0 auto";
        ulArea.style.float = "none";
    }
}
window.addEventListener("width" , headerHeight)
function headerHeight() {
    if (document.getElementById("header").width < 990px) {
        header.style.height = "100px";
    } else {
        header.style.height = "220px";
    }
}

您的代码有一些问题:

  1. 您需要使用resize事件(没有width事件(。
  2. 我认为 logo变量是未定义的,您是指 HaLogo吗?
  3. ulArea未定义。
  4. 您需要使用元素的 .style.width属性(不存在.width(。
  5. 您需要将元素的宽度解析为使用parseInt的整数。如果您不解析它,您将将诸如'50px'之类的字符串与INT 990进行比较。
  6. < 990px更改为< 990(删除px(。

您应该使用if语句的if (parseInt(document.getElementById("header").style.width) < 990) {和第二个活动侦听器的window.addEventListener("resize", headerHeight);

我认为您实际在寻找的是调整大小事件而不是宽度:

window.addEventListener('resize', function(event){
  // do stuff here
});

最新更新