2011-11-14 42 views
1

我正在嘗試使用CSS屬性進行計算,但它不返回任何內容。使用jQuery和CSS屬性進行計算

我認爲這可能是因爲CSS屬性返回'200px'而不是簡單'200'。任何人都可以提出解決辦法嗎?非常感謝。

windowHeight = $(window).height(); // This works 
logoHeight = $('.home h1').css('height'); // This returns '200px' 
logoPosition = windowHeight * 0.5 - logoHeight; 
+0

從CSS請求中的值是包含「PX」你需要通過JS yuorself替換此或解析的數量的字符串。 – Smamatti

+1

請注意,有更好的方式來垂直中心的東西比javascript。 – Eric

回答

1

試試這個,

windowHeight = $(window).height(); // This works 
logoHeight = $('.home h1').css('height'); // This returns '200px' 
logoPosition = windowHeight * 0.5 - parseInt(logoHeight); 
+0

非常感謝 - 這是最有用的,因爲它可以幫助我理解問題以及如何將其他CSS放入一個整數。 – SparrwHawk

5

您需要將「200px」字符串轉換爲整數;使用parseInt

windowHeight = $(window).height(); // This works 
logoHeight = parseInt($('.home h1').css('height'), 10); // This returns '200px' 
logoPosition = windowHeight * 0.5 - logoHeight; 

否則,你的總和windowHeight * 0.5 - logoHeight將返回NaN(非數字)。

重要的是總是指定基數作爲parseInt的第二個參數,否則您會發現像;

parseInt("022") == 18; // true 
3

你應該只能夠在<h1>元素上使用height()

windowHeight = $(window).height(); // This works 
logoHeight = $('.home h1').height(); 
logoPosition = windowHeight * 0.5 - logoHeight; 
+0

這比使用'css('height')'更好,因爲你更好地使用jQuery – HerrSerker

+0

這很好,謝謝。我將來會使用它。 – SparrwHawk

0

這裏有一些其他的例子向您展示如何使用其他CSS屬性和jQuery方法。 Check our jQuery style properties

var element = $('#element'); 
var borderLeftWidth = parseInt(element.css('borderLeftWidth'), 10); // css border-left-width 
var borderRightWidth = parseInt(element.css('borderRightWidth'), 10); // css border-right-width 
var fullWidth = element.outerWidth(false); // includes padding and border but not margins