javascript - 如何为不同的屏幕尺寸编写响应式文本

标签 javascript jquery responsive-design

如果我想制作响应式文本,我可能会写这样的内容:

$(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/

相关文章:

javascript - sequelize 上的多个外键(一对多或多对多)?

javascript - 使用 async.each 和 promises - async each 永远不会停止

javascript - jquery/css 将文本自底向上包装

javascript - Jquery keypress() 事件没有捕获 Tab 键码

css - 如何在具有 40px 填充的父 div 中将 div 设置为 100% 宽度

javascript - ExtJS 名称未定义错误

javascript - 使用冒泡关闭函数

php - 当我点击浏览器的后退按钮时,如何在主页上重定向

html - 未知元素超出窗口

javascript - 如何在显示下拉菜单项时使导航栏响应