Geo*_*off 5 javascript css conditional image responsive-design
我正在改造现有网站的自适应布局.基本上在500px,该网站变为100%宽度的移动风格布局.通常我会使用ems,但正如我所说,我正在改装.
我知道如何有条件地加载js和css,但html和图像怎么样?
在网站的主页上有一个填满屏幕的大图像,在我的小屏幕布局上我不需要它,所以如果浏览器宽度超过500px,我希望它加载.麻烦的是我无法<img src="..." />在js中存储等等,因为它是动态加载的PHP.客户端通过wordpress admin控制图像.
任何想法将不胜感激.谢谢
这适用于一两件事。对于站点范围的图像加载首选项,还有其他解决方案。
有关示例,请参阅此 codepen 。我已经在开发工具中检查了它,以确保大图像不会加载。
因此,您可以找到窗口宽度并将.width()其存储在名为(无论您想要什么)的变量中,我称之为它 wWidth。然后是 if 语句。如果窗口宽度大于 1200px(这很糟糕,你不能使用 em) ---那么,加载这个图像 - 否则,加载这个较小的图像。要将其放入 DOM,您可以将 html 附加到现有的 div 中:.appendTo()
$(function () {
var wWidth = $(window).width();
if (wWidth > 1200) {
$('<img alt="larger image" src="http://placehold.it/1200/1200"/>').appendTo('.sidebar');
$('.sidebar a').hide();
} else {
$('<img alt="smaller image" src="http://placehold.it/600/600" />').appendTo('.sidebar');
}
});
Run Code Online (Sandbox Code Playgroud)
这个例子是关于地图的......所以如果他们想加载谷歌地图,我有一个链接,他们可以按下来加载更好的地图。(但是,如果窗口很大,我就不需要那个链接 - 所以我用.hide()
截至 2014 年 4 月,我一直在使用 attr() 切换 src,这样,您就拥有了移动图像,然后如果它是大屏幕,您可以插入较大图像的源...但是然后您加载 2图片...所以你可以加载一个 1px x 1px 的空白 gif 或其他东西来开始...并给它一个接近你想要的比例的宽度和高度...
<div class='image-w thing' id='target01'>
<!-- standard image for small screens or a blank gif or something -->
<img src='http://placehold.it/640x640&text=Default-image' alt='' />
</div>
Run Code Online (Sandbox Code Playgroud)
var imageSizeThing = function() {
var windowWidth = $(window).width();
if ( windowWidth < 501 ) {
// if you start with a blank gif or something
$('#target01 img').attr('src','http://placehold.it/640x640&text=Default-image');
} if ( windowWidth > 500 ) {
$('#target01 img').attr('src','http://placehold.it/1000x1000');
} if ( windowWidth > 900 ) {
$('#target01 img').attr('src','http://placehold.it/1800x1800');
} if ( windowWidth > 1200 ) {
$('#target01 img').attr('src','http://placehold.it/2400x2400');
}
};
// call it on DOM ready, and if it makes sense, when the window resizes
$(document).ready(imageSizeThing);
$(window).resize(imageSizeThing);
Run Code Online (Sandbox Code Playgroud)