如果我想制作响应式文本,我可能会写这样的内容:
$(window).resize(function ()
{
if $(document).width() <= 320) {
$('#mydiv').html('something')
}
if $((document).width() > 320) && (document).width() <= 480)) {
$('#mydiv').html('something longer')
}
if $((document).width() > 480) && (document).width() <= 768)) {
}
//and so on
}
我不认为这是最有效的(而且代码很困惑) - 我认为必须有一种方法可以使它更容易 - 让我们假设我可以编写这个存储所有数据的对象:
var divTextPerScreenWidthMap = {
{'360','click'},
{'480','click it'},
{'768','click it right'},
{'1024','you know you want to click it'},
{'1280','click this button which is very long will help you'}
}
完成此操作后,是否可以编写一个简单的函数来获取这些数据并简化我的多条件函数?某种方式告诉 javascript 如何构建我需要的特定函数?
类似这样的东西,但是在真实的代码中:
for (objects in divTextPerScreenWidthMap) {
create If Statement for Nth Object(object)
}
谢谢, 阿隆
最佳答案
我认为使用这样的查找表有点矫枉过正。请注意,如果正确使用 else if
,您的代码会变得更加简单。
if $(document).width() <= 320) {
$('#mydiv').html('something')
} else if ($(document).width() <= 480) {
$('#mydiv').html('something longer')
} else if ($(document).width() <= 768) {
...
}
关于javascript - 如何为不同的屏幕尺寸编写响应式文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9179901/