问题
I want to load different images based on screensize, and thought replacing text in a filename with javascript would do the trick elegantly, as long as I've got corresponding images properly named. I'm close with this, but close won't cut it.
http://jsfiddle.net/B7QhZ/2/
Javascript:
if ($(window).width() > 960) {
$("div:contains(_small.jpg)").html(function (i, currentVal) {
return currentVal.replace("_small.jpg", "_large.jpg");
});
}
HTML:
<img src="...test-image_small.jpg" />
As you can see in my fiddle, i've got it working on text, but not the filename.
ps - I specifically don't want to load images as background-image in media-queried classes.
回答1:
Complete function:
if ($(window).width() > 960) {
$("img[src$='_small.jpg']").each(function() {
var new_src = $(this).attr("src").replace('_small', '_large');
$(this).attr("src", new_src);
});
} else {
alert('Less than 960');
}
回答2:
I want to load images based on screensize
Set the width and height of CSS for div to 100%
CSS
div {
width: 100%;
height: 100%;
}
JSFiddle
来源:https://stackoverflow.com/questions/23947243/replace-part-of-filename-with-javascript