簡體   English   中英

滾動eventListener停止工作

[英]Scroll eventListener stops working

問題是當我啟用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"; } } 

我認為您實際上正在尋找的是resize事件,而不是width事件:

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

您的代碼存在一些問題:

  1. 您需要使用resize事件(沒有width事件)。
  2. 我認為未定義logo變量,您是說HaLogo嗎?
  3. ulArea未定義。
  4. 您需要使用元素的.style.width屬性( .width不存在)。
  5. 您需要使用parseInt將元素的寬度解析為一個整數。 如果您不解析它,則將類似'50px'的字符串與int 990
  6. < 990px更改為< 990 (刪除px )。

您應該以if (parseInt(document.getElementById("header").style.width) < 990) {對於您的if語句和window.addEventListener("resize", headerHeight); 為您的第二個事件偵聽器。

暫無
暫無

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

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