根据屏幕宽度加载不同的图像

时间:2012-08-20 14:21:59

标签: javascript html ajax xhtml responsive-design

让我们假设我正在调用像

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

最后宽度为“1400”的情况下,如何制作“1400”,60%的用户屏幕宽度呢?

3 个答案:

答案 0 :(得分: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> 

答案 1 :(得分:0)

另一种方法是使用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是更好的方法。

答案 2 :(得分:0)

在我的情况下,我添加了我现在提供的答案,因为我的实际图像字符串比他的答案允许的更复杂,因为它在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>