Replace part of filename with javascript

本小妞迷上赌 提交于 2019-12-11 15:25:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!