我正在尝试为我的自适应网站动态更改图片。当我调整浏览器大小时,没有任何反应。我的代码有什么问题吗?
public void getItemType(final Context context,final ItemTypeRequestUIListener uiListener) {
if (PhoneUtils.isNetworkAvailable(context) == true) {
new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... params) {
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(AppConstants.URL_DO_LIST_LOOKUP);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
request.setEntity(new StringEntity(AppConstants.URL_DO_LIST_LOOKUP_ITEM_JSON_PARAM_FORMAT));
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity.getContentLength() != 0) {
Reader objectReader = new InputStreamReader(response.getEntity().getContent());
char[] buffer = new char[(int) response.getEntity().getContentLength()];
objectReader.read(buffer);
objectReader.close();
String str = new String(buffer);
str = str.replace("?", "");
Log.i("AMIRA", "TYPES RESPONSE : " + str);
JSONObject jsonResponse = new JSONObject(str);
uiListener.onRequestCompleted(ItemTypeResponse.parseJSONObject(jsonResponse),null);
}
} catch (Exception e) {
e.printStackTrace();
uiListener.onRequestCompleted(null,AppError.GENERAL_ERROR);
}
return null;
};
}.execute();
} else {
uiListener.onRequestCompleted(null, AppError.NO_INTERNET);
}
}
我的HTML如下:
<script type = "text/javascript">
$(window).ready(function() {
var wi = $(window).width();
$(window).resize(function() {
var wi = $(window).width();
if (wi <= 480){
document.getElementsByClassName('party')[0].src="images/1.jpg"
}
else {
document.getElementsByClassName('party')[0].src="images/5.jpg"
}
});
});
答案 0 :(得分:2)
图片元素包含类img-responsive
而不是party
。你也在混合javascript和jquery。我宁愿建议你使用纯JS或jquery:
$(window).resize(function() {
var wi = $(window).width();
$('.img-responsive').attr('src',wi < = 480 ? "images/1.jpg" : "images/5.jpg");
});
答案 1 :(得分:1)
$(window).ready(function() {
$(window).resize(function() {
var wi = $(window).width();
if (wi <= 480){
$("#main").find("img").attr("src","images/1.jpg")
}
else {
$("#main").find("img").attr("src","images/5.jpg");
}
});
});
尝试使用此代码,您也会不必要地声明wi
两次。
答案 2 :(得分:0)
正如Milind Anantwar建议的那样,你试图用“派对”类来设置div的src。您应该使用“img-responsive”类的src-attribute设置图像。
尝试下面的plunkr,并检查控制台中的日志,这些日志显示您实际上正在抓取jQuery代码中的错误元素。
if (wi <= 480) {
var partyElement = document.getElementsByClassName('party')[0];
console.log(partyElement);
document.getElementsByClassName('img-responsive')[0].src = "images/1.jpg"
} else {
var partyElement2 = document.getElementsByClassName('party')[0];
console.log(partyElement2)
document.getElementsByClassName('img-responsive')[0].src = "images/5.jpg"
}
Heres是一名傻瓜 http://plnkr.co/edit/wBVt4qQZdOOrw94rHJFZ?p=preview