我正试图找出一个我遇到的小问题的等式。我不太擅长弄清楚这些类型的东西,但我知道我以前用不同的数字来完成它。
基本上,我想弄清楚:
if 360px = 100%;
and 959px = 160%;
then 720px = X;
720px是任意数字。我知道360px应该是100%的字体大小,而959px应该是160%的字体大小。我希望在屏幕放大或缩小时(通常在加载时)更改正文字体大小,并且我想在中间找出任何字体大小百分比。< / p>
我想将其插入到javascript数学函数中,如下所示:
function widthToPerc(){
var width = $(window).width();
var toPerc = // THIS FORMULA RIGHT HERE TO GET A PERCENTAGE
$('body').css({"font-size" : toPerc + "%"});
}
然后在窗口加载和窗口调整大小时启动它。
答案 0 :(得分:3)
如果你的方程是线性的,那应该是解决方案:
f(x) = a*x + b
f(360) = 100
f(959) = 160
a * 360 + b = 100
a * 959 + b = 160
解决此问题后,您将获得a ~= 0.1
和b ~= 63.94
因此,结果:
var ToPerc = width * 0.1 + 63.94; // 99.94% for 360px; 159.84% for 959px
如果您需要更多精度求解更多小数
答案 1 :(得分:1)
function calculate(w){
//Assuming the numbers you provided and w coming without px
var d = 959-360;
var p = 160-100;
var c = w - 360;
var cp = p*c/d + 100
return cp
}
答案 2 :(得分:0)
OnLoad,您将获得初始$(窗口).width()。你将把它存储在一个全局变量中,正如我刚才开始说的那样。
var initWidth = $(window).width();
然后功能:
function widthToPerc(){
var width = $(window).width();
var diff = width - initWidth;
var toPerc;
if(diff > 0){ //window is bigger after resizing
toPerc = Math.floor((diff / initWidth) * 100) + 100;
}
else{ //window is smaller after resizing
diff = Math.abs(diff);
toPerc = Math.abs(Math.floor((diff / initWidth) * 100) - 100);
}
$('body').css({"font-size" : toPerc + "%"});
}
因此,假设您有600作为初始宽度,用户调整浏览器大小以使其更大。现在宽度是800.
所以:
var initWidth = 600;
var width = 800;
var diff = 200; // 800 - 600
diff > 0 // true
toPerc = 0.3 // 200 / 600
toPerc = 30 // after *100 and rounded down
toPerc = 130 // 30 + 100
//the window is a 30% bigger than it was intially
$('body').css({"font-size" : "130%"});
现在让我们看看窗口何时被调整大小并变得更小
var initWidth = 600;
var width = 400;
var diff = -200; // 400 - 600
diff < 0 // true
diff = 200 //after Math.abs
toPerc = 0.3 // 200 / 600
toPerc = 30 // after *100 and rounded down
toPerc = -70 // 30 - 100
toPerc = 70 // after Math.abs
//the window is a 30% smaller than it was intially
$('body').css({"font-size" : "70%"});
答案 3 :(得分:0)
我不确定这是不是你的意思,但这是我理解的方式。
这对我来说似乎更像是一个数学问题,所以让我们将像素和百分比转化为分数:
p1 = (360,100)
p2 = (959,160)
p3 = (720,y3)
现在我们在720
和360
之间找到了959
的百分比:
(720-360)/(959-360) = around 60%
要获得y3
,我们会这样做:
((160-100)*.60)+100 = 136
使此功能适用于360
和959
function widthToPerc(){
var width = $(window).width();
var toPerc;
var minX = 360;
var maxX = 959;
var minY = 100;
var maxY = 160;
if (width >= 360) {
toPerc = min;
}
else if (width <= 959) {
toPerc = max;
}
else {
toPerc = ((maxY-minY)*((width-minX)/(maxX-minX)))+minY;
}
$('body').css({"font-size" : toPerc + "%"});
}