2016-08-17 273 views
-1

我使用Waypoints.js(http://imakewebthings.com/waypoints/api/waypoint/ - 無框架依賴項)。更改CSS屬性

現在我想改變航點上的CSS屬性。以模塊化方式處理我的代碼的最佳方式是什麼?

HTML:

<div class="header" id="header"></div> 
<button class="menu"></button> 

JS:

var waypoint = new Waypoint({ 

    element: document.getElementById('direction-waypoint'), 
    handler: function(direction) { 
     if (direction == 'down') { 
      document.getElementById("header").setAttribute("style", "position: fixed;"); 
      document.getElementById("header").style.backgroundColor = "white"; 
      document.getElementById("menu").getElementsByTagName("li")[0].setAttribute("style", "background-color: #999;"); 
      document.getElementById("menu").getElementsByTagName("li")[1].setAttribute("style", "background-color: #999;"); 
      document.getElementById("menu").getElementsByTagName("li")[2].setAttribute("style", "background-color: #999;"); 

     } else { 
      document.getElementById("header").setAttribute("style", "position: absolute;"); 
      document.getElementById("menu").getElementsByTagName("li")[0].setAttribute("style", "background-color: default;"); 
      document.getElementById("menu").getElementsByTagName("li")[1].setAttribute("style", "background-color: default;"); 
      document.getElementById("menu").getElementsByTagName("li")[2].setAttribute("style", "background-color: default;"); 

     } 
    } 

}); 
+3

爲什麼不添加和刪除類呢?在JavaScript中設置靜態樣式通常是不好的做法。 – Ryan

+0

你給這個樣式賦值。 –

+0

@Ryan Ok,那麼我甚至不需要if語句,對吧? – halp

回答

-1

你不喜歡這樣。

var waypoint = new Waypoint({ 

    element: document.getElementById('direction-waypoint'), 
    handler: function(direction) { 

    var headerElem = document.getElementById("header"), 
    menuElem = document.getElementById("menu"); 

     if (direction == 'down') { 
      ) 

    headerElem.style.position = 'fixed'; 
    headerElem.style.background-color = 'white'; 

    menuElem.children[0].style.background-color = '#999'; 
    menuElem.children[1].style.background-color = '#999'; 
      menuElem.children[2].style.background-color = '#999'; 

     } else { 

    headerElem.style.position = 'absolute'; 

    menuElem.children[0].style.background-color = ''; 
    menuElem.children[1].style.background-color = ''; 
    menuElem.children[2].style.background-color = ''; 

     } 
    } 

}); 

如果你做了一個console.dir,你可以看到所有的元素屬性。這是評估使用vanilla JavaScript時的一些好方法。

var headerElem = document.getElementById("header"); 

console.dir(headerElem); 
+1

不熟悉Waypoints,但如果這是純JS,那麼你的'background-color'應該是'backgroundColor'。 –

+0

'背景顏色'是無效的語法,我不知道這是如何比問題中已有的更好。 – Ryan