2015-09-12 64 views
4

我正在重建我的網頁,使其更加優雅,因此我決定在用戶​​向下滾動時更改頂部欄,使其更小並隱藏其中的某些元素。當您向下滾動時,我會觸發該功能,但由於某種原因,它不會執行任何操作。向下滾動時更改樣式(javascript)

我的HTML:

<div class="maindiv"> 
     <img src="media/cgaline.png" id="cgalinepic" class="cgalinepic"> 
     <a id="right-panel-link" href="#right-panel"><img src="media/menu.png" id="open_menu_button" width="50px" height="50px"></a> 
     <h2 class="h1-3" id="h1-3"> 
      We are not in danger, we ARE the danger. 
     </h2> 
</div> 

我不知道發生了什麼錯誤的,因爲我奉獻了我大部分時間在PHP,我發現JavaScript的有點辛苦。

我也試着這樣做:

$('#maindiv').style.height = "50px"; 

但不工作也沒有。

我最後的javascript代碼(感謝鷺和伊利亞Sviridenko):

var div = $('.maindiv'); 
var pic = $('.cgalinepic'); 
var menu = $('.open_menu_button'); 
var text = $('.h1-3'); 

$(function(){ 
    var div = $('.maindiv'); 
    var pic = $('#cgalinepic'); 
    var menu = $('#open_menu_button'); 
    var text = $('#h1-3'); 

    $(document).scroll(function() { 
     var lastScrollTop = 0; 
     $(window).scroll(function(event){ 
     var st = $(this).scrollTop(); 
     if (st > lastScrollTop){ 
      div.css("height", "50px"); 
      pic.css({ width : "400px", height : "50px" }); 
      text.hide(); 
      menu.css("top", "0px"); 
     } else { 
      div.css("height", "140px"); 
      pic.css({ width : "800px", height : "100px" }); 
      text.show(); 
      menu.css("top", "47px"); 
     } 
     lastScrollTop = st; 
     }); 
    }); 
}); 
+2

您可以添加HTML此 – Chrillewoodz

回答

3

只有在DOM準備好之後,纔可以使用jQuery。包裝你的JS代碼:

$(function(){ 
    ... 
}); 

最終的解決方案,與鷺代碼:

$(function(){ 
    var div = $('#maindiv'); 
    var pic = $('#cgalinepic'); 
    var menu = $('#open_menu_button'); 
    var text = $('#h1-3'); 

    $(document).scroll(function() { 
     div.css("height", "50px"); 
     pic.css({ width : "400px", height : "50px" }); 
     text.css("visibilty", "hidden"); 
     menu.css("top", "0px"); 
    }); 
}); 
+0

好吧,一切正常,除了div沒有改變它的高度PS:沒關係,我修正了它,一切正常。 – KeepoN

3

您已經使用jQuery。
只需繼續使用jQuery API

div.css("height", "50px"); 
pic.css({ width : "400px", height : "50px" }); 
text.css("visibilty", "hidden"); // did you mean to hide the text completly? If so use text.hide(); 
menu.css("top", "0px"); 
+0

仍然沒有工作 – KeepoN

+1

變化:VAR股利= $( '#maindiv' ); to var div = $(「。maindiv');你沒有一個id,但是class。類用點前綴 - 」.maindiv「和id用hash前綴 - 」#maindiv「 – Sagi