简体   繁体   中英

Load different image based on screen width

Lets assume that I'm calling an image like

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

Where the width is "1400" at the end, how can I make that "1400", 60% of the users screen width instead?

You should set the parameter in JavaScript. Check the source of Google Books.

<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> 

Another approach is to use CSS instead of 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);
    }
}
...

Though charts tend to be part of the content, so using CSS and background-image isn't really appropriate, and JS + img.src is the better approach in this case.

In my case I sort of added my answer to the one that noway had provided since my actual image string was a bit more complicated than his answer would allow for as it was inside a jsp loop.

<%
    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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM