JavaScript宽高比计算器

时间:2017-09-18 19:21:10

标签: javascript jquery html

我尝试创建一个JavaScript条件,它使用函数的结果来显示HTML代码的一部分或另一部分。

我发现这段代码可以计算Gist上的宽高比:

/* euclidean GCD (feel free to use any other) */
function gcd(a,b) {if(b>a) {temp = a; a = b; b = temp} while(b!=0) {m=a%b; a=b; b=m;} return a;}

/* ratio is to get the gcd and divide each component by the gcd, then return a string with the typical colon-separated value */
function ratio(x,y) {c=gcd(x,y); return ""+(x/c)+":"+(y/c)}

/* eg: 
> ratio(320,240)
"4:3"
> ratio(360,240)
"3:2"
*/

我想要的是计算屏幕宽高比,如果屏幕比例为16:9则运行以下代码:

<img src="https://via.placeholder.com/1920X1080.jpg">

如果纵横比为4:3,则应加载:

<img src="https://via.placeholder.com/1024X768.jpg">

这可以用于多种屏幕分辨率。

这是一个JSBin链接:http://jsbin.com/fedipuqasi/edit?html,js,output

我对StackOverflow做了一些研究,但找不到任何完整的例子,不幸的是,我的JavaScript技能似乎生锈了。

如果我需要提供更多详细信息,请与我们联系。

2 个答案:

答案 0 :(得分:3)

这应该有效。

&#13;
&#13;
function gcd(a, b) {
  if (b > a) {
    temp = a;
    a = b;
    b = temp
  }
  while (b != 0) {
    m = a % b;
    a = b;
    b = m;
  }
  return a;
}

/* ratio is to get the gcd and divide each component by the gcd, then return a string with the typical colon-separated value */
function ratio(x, y) {
  c = gcd(x, y);
  return "" + (x / c) + ":" + (y / c)
}

var ratio = ratio(screen.width, screen.height)
var imgContainer = document.querySelector('#img')

switch (ratio) {
  case "16:9":
    imgContainer.innerHTML = '<img src="https://via.placeholder.com/1920X1080.jpg">'
    break
  case "4:3":
    imgContainer.innerHTML = '<img src="https://via.placeholder.com/1024X768.jpg">'
    break
  default:
    imgContainer.innerHTML = '<img src="https://via.placeholder.com/other.jpg">'
    break    
}
&#13;
#img {
  width: 300px;
  height: 300px;
}

#img img {
  display: block;
  max-width: 100%;
}
&#13;
<div id="img">

</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您显示的代码用于以特定格式显示比率,例如“4:3”。您无需使用它进行测试。

比率只是宽度除以高度,所以只需检查结果

tableView.reloadData()

如果你不想使用一堆if语句,你可以将所有url存储在一个比例为属性名称的对象中。然后使用计算出的比率来获得正确的URL。

var img = new Image();
var widescreen = 16/9; 
var standard = 4/3;

var userRatio = window.screen.width / window.screen.height;

if(userRatio == widescreen){
  img.src = 'https://via.placeholder.com/1920X1080.jpg';
} else if( userRatio == standard ){
  img.src = 'https://via.placeholder.com/1024X768.jpg';  
} else {
  //user using different screen resolution
  img.src = 'https://via.placeholder.com/other.jpg';  
}

document.body.appendChild(img);
相关问题