【问题标题】:Load different image based on screen width根据屏幕宽度加载不同的图像
【发布时间】:2012-08-20 14:21:58
【问题描述】:

假设我正在调用像这样的图像

<img src="http://server:8080/graphs/ChartGen?PID=982&minutes=480&height=30&width=1400" />

最后宽度为“1400”的地方,我怎样才能使“1400”,即用户屏幕宽度的 60% 代替?

【问题讨论】:

  • 不知道我是否理解你的问题,但也许 css 会有所帮助:img {width:60%}
  • 不幸的是,图像的来源要求我向它传递一个值(最后的宽度 = 1400),因此如果我在 900 像素宽的显示器上运行代码,1400 可能太大了。

标签: javascript html ajax xhtml responsive-design


【解决方案1】:

您应该在 JavaScript 中设置参数。检查 Google 图书的来源。

<script language="javascript" type="text/javascript">     

var url= "http://server:8080/graphs/ChartGen?PID=982&minutes=480&height=30&width=" + (screen.width * 0.60);     


</script> 

【讨论】:

  • 不幸的是,此解决方案不起作用,因为 PID / 分钟数也需要根据用户偏好进行更改。这些值是通过循环加载的。
  • 我相信你也可以用另一个在链接的 Click 事件上触发的 JS 函数来设置 PID 和分钟参数?
【解决方案2】:

另一种方法是使用 CSS 代替 JS:

@media screen and (min-width: 800px) {
    #Chart {
        background-image: url(//server:8080/chart/982/480/:height:30/:width:480);
    }
}
@media screen and (min-width: 768px) and (max-width: 799px) {
    #Chart {
        background-image: url(//server:8080/chart/982/480/:height:30/:width:460);
    }
}
...

虽然图表往往是内容的一部分,但使用 CSS 和 background-image 并不是很合适,在这种情况下 JS + img.src 是更好的方法。

【讨论】:

    【解决方案3】:

    在我的情况下,我将我的答案添加到了现在提供的答案中,因为我的实际图像字符串比他的答案要复杂一些,因为它在 jsp 循环中。

    <%
        for (int i = 0; rs.next(); i++) {
    %>
    
    //Other formatting
    <div class="ProgramGraph"> 
    <script type="text/javascript"> document.write("<img src=\"http://server07:8080/graphs/ChartGen?PID=<%= rs.getInt("PID")%>&minutes=<%out.print(timeSelected * 60);%>&height=30&width=" +screen.width*.60 +"\" />");</script></div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-30
      • 1970-01-01
      • 1970-01-01
      • 2014-02-21
      • 1970-01-01
      • 2013-05-23
      相关资源
      最近更新 更多