2011-03-18 252 views
5

在CSS中,我用body:after來添加內容,我想在jQuery中獲取它的高度。我該怎麼做?選擇:僞類後元素

我從here讀取這樣的僞元素是修改,因此不可選?我似乎甚至無法使用$("body > :last-child")來選擇應該是:after的最後一個孩子?

回答

4

請注意,您使用:aftercontent添加的內容不是node - 它不是文檔中的元素或文本。你可以用FireBug看到這個:在這個屏幕截圖中,我的HTML包含單詞「hello」,但是單詞「world!」。

Screenshot of a Hello World page where the word World is added with CSS content. FireBug is open, clearly showing that the CSS content does not add an element to the DOM

你可以做的是使用getComputedStyle找出內容是什麼,就像下面的例子:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" > 
    <head> 
     <title>Select :after pseudo class/element</title> 
     <style type="text/css"> 
     #msg:after { 
      content:" World!" 
     } 
     </style> 
     <script type="text/javascript"> 
     window.onload = function() { 
      if(window.getComputedStyle) { 
       var element = document.getElementById("msg"); 
       var style = window.getComputedStyle(element,':after') 
       alert(style.content); 
      } 
      else { 
       alert("This browser sucks!"); // ;) 
      } 
     } 
     </script> 
    </head> 
    <body> 
     <h1> 
      <span id="msg">Hello</span> 
     </h1> 
    </body> 
</html> 

...不幸的是,這給你訪問使用CSS添加到內容但不是高度:(

+6

我喜歡你的錯誤信息:) – 2012-10-19 05:45:23

+0

@MikeHometchko - 好吧,我喜歡你,那麼,好友! :d – 2012-10-19 18:06:31