使用javascript修改网址?

时间:2014-04-06 20:36:32

标签: javascript url

我根据用户的屏幕尺寸创建了动态图片网址 如何修改网址,以便在最后添加屏幕尺寸?

原始网址格式:

http://abc.net/stakes-html/images/backgrounds/2560by1440/3.jpg
http://abc.net/stakes-html/images/backgrounds/2560by1440/abcr.jpg
http://abc.net/stakes-html/images/backgrounds/2560by1440/pkjg342.jpg

最终网址:

http://abc.net/stakes-html/images/backgrounds/2560by1440/3-1240by768.jpg
http://abc.net/stakes-html/images/backgrounds/2560by1440/abcr-1240by768.jpg
http://abc.net/stakes-html/images/backgrounds/2560by1440/pkjg342-1240by768.jpg

2 个答案:

答案 0 :(得分:0)

假设图像大小是动态生成的(如URL重写+图像生成器), 您始终可以动态生成图像路径,如下所示:

'http://abc.net/stakes-html/images/backgrounds/2560by1440/3-' + window.innerWidth + 'x' + window.innerHeight + '.jpg'

依此类推,其中window.innerWidth是当前窗口宽度(以像素为单位),window.innerHeight是当前窗口高度(以像素为单位)。

无论如何,请考虑使用Media Queries,因为它们允许根据用户分辨率动态显示图片,而无需使用javascript。 媒体查询works in all major browsers现在。

答案 1 :(得分:0)

var index = url.lastIndexOf(".");
var newUrl = url.substring(0, index) + "-" + window.innerWidth + "by" + window.innerHeight + url.substring(index, url.length)
console.log(newUrl); //as you can see you have the new url with the size