2014-11-24 42 views
0

我需要設置background-color屬性到整個身體,但我的代碼似乎不工作 我學習jQuery的,但我仍然是一個新手集background-color屬性在整個文檔

我使用的選擇該呼叫的 body元素,並應用到它的風格

<html> 
    <head> 
     <title></title> 
     <script type="text/javascript" src="jquery-1.11.1.js"> 
     </script> 
     <script type="text/javascript"> 
     jQuery(document).ready(function(){ 
      $(this).css("background-color","green"); 
     }  
     ); 

     </script> 
    </head> 
    <body> 
     <ul id="destinations"> 
      <li>First</li> 
      <li>Second</li> 
      <li>Third</li> 
      <li>Fourth</li> 
      <li>Fifth</li> 
      <li class="six">Sixth</li> 
     </ul> 
     <p>This is another parragraph</p> 
     <p>and this is another more</p> 
    </body> 
    </html 

> 
+0

據我所知,你在學習jQuery的,但如果你想設置背景的身體,最好使用CSS。通過jQuery實際*需要的事情來學習jQuery。 – 2014-11-24 05:37:49

回答

3

在jQuery中,$(這)是指調用當前函數中的DOM元素。由於您在文檔'ready'事件中調用$(this),$(this)引用文檔(DOM),這就是您的代碼無法工作的原因。

要應用CSS規則,您必須改爲使用body標籤。因此,你必須這樣改變:

$(this).css("background-color","green");

到:

$('body').css("background-color","green");

+1

它更好地添加一些解釋以及爲什麼代碼張貼在問題不起作用.. :) – 2014-11-24 03:41:04

+0

你是對的。添加了原始代碼無法工作的簡要說明。隨意建議進一步編輯。 – tkounenis 2014-11-24 04:02:13

+0

會做.. – 2014-11-24 04:09:39

3

您應選擇體,並設置有背景

$('body').css("background-color","green"); 
+0

感謝朋友。我認爲這是(這個) – user3678471 2014-11-24 03:42:15

3

*如果你想設置可能不會改變的背景顏色,那麼你可以使用,

$('body').css("background-color","color-name"); 
3
  • 如果你想改變點擊按鈕的背景顏色,那麼你可以使用,

    $(document).ready(function(){ 
    
        $("button").click(function(){ 
    
        $("p").css("background-color","yellow"); 
    
        }); 
    
    });