2011-09-18 88 views
0

我試圖根據視口大小生成動態調整大小的照片滑塊,但保持4:3的比率,而不考慮視口尺寸。JQuery Maths:根據以前計算的值計算比率

我正在瀏覽的網頁是在這裏: http://steph-morris.com/thenovel_III.html

目前正在通過抓取視口寬度和減去菜單欄的大小,像這樣計算的寬度:

$(document).ready(function(){ 
    var height = $(window).height(), width = $(window).width(); 
    $('img').css('width', (width - (281+(height*0.32))) + 'px'); 
    }); 

(其中一個菜單的寬度爲281像素,另一個菜單的高度爲0.32)。

我需要計算高度與寬度的比例爲4:3。

我全新的jQuery的數學和一直沒能得到一個工作嵌套式,做類似

$('img').css('height', ((width - (281+(height*0.32))*thecorrectratio) + 'px'); 

而且,這不是一個有效的approach-我應該存儲的結果在「寬度」計算,我認爲並計算其多爲

$('img').css('height', (widthvalue*thecorrectratio) + 'px'); 

但我也不知道怎麼做,使用jQuery。 (a)如何編寫一個好的嵌套方程來計算'高度'的值,或者(b)如何保存'寬度'方程的結果,以便它可以再次使用,顯然(c)計算4:3比率的正確方法。

+0

這實際上是一個JavaScript問題,甚至只是一個數學問題。 JQuery沒有數學。 –

+0

我曾經回答過一個似乎非常相似的問題:http://stackoverflow.com/questions/6565703/math-algorithm-fit-image-to-screen-retain-aspect-ratio/ – davin

回答

1

你可以用一個函數寫一個公式:

$(document).ready(function(){ 
    function height43(width){ 
     return Math.floor(parseInt(width)/4*3); 
    } 
    var menuWidth = 281; 
    var slideWidth = $(window).width()-menuWidth; 
    var slideHeight = height43(slideWidth); 
    // all variables and functions declared directly inside some brackets 
    // are available everywhere inside or subinside these brackets so you can reuse them 
    function anotherFunctionSample(){ 
     alert('slideHeight : '+slideHeight); 
     alert('new calculation with another width : '+height43(700)); 
    } 
    anotherFunctionSample(); 
}); 

那就請看看JavaScript的基礎上試圖去別處之前...也許關於跨產品的一些主要的數學課;) 然後jQuery是'只是'一個javascript包裝,它可以通過不同的瀏覽器兼容性解釋不同的事情來幫助我們完成不同的工作......努力工作

+0

感謝有關如何構造函數和方程,這是行之有效的! – Ila