JavaScript 宽高比计算器

标签 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 技能似乎已经生疏了。

如果我需要提供更多详细信息,请告诉我。

最佳答案

这应该有效。

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    
}
#img {
  width: 300px;
  height: 300px;
}

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

</div>

关于JavaScript 宽高比计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46286710/

相关文章:

javascript - 使用 jQuery 中的 text() 方法将函数中的字符串写入 div 元素

Java 的 Random 类的 Javascript 实现将使用相同的种子生成相同的序列

javascript - 将“加载更多”添加到使用 $.getJSON 从 Google 电子表格接收的数据输出中

css - 我需要一个 div 坐在另一个 div 的 Angular 落,在另一个 div 之上

javascript - 如何知道你的递归函数已经结束

javascript - Node.js,MYSQL - 如何仅获取没有列名的数据

javascript - 设置一个 on.click 以获得更多操作 - javascript 和 jQuery

jquery - 通过 2 个选择列表过滤 html 表格

javascript - 如果标量变量 > 0,Perl 更改图像/css

html - 如何使用左右浮动和垂直居中对齐?