如何根据用户是在桌面浏览器还是移动浏览器上访问,在 css 中指定不同的图像 [英] how to specify a different image in css depending if the user visits on a desktop or a mobile browser

查看:27
本文介绍了如何根据用户是在桌面浏览器还是移动浏览器上访问,在 css 中指定不同的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是一个关于移动设备 css 的问题,

Just a question about css for mobile devices,

我的网站上有一张 1260 像素宽的图片,当我在手机上查看它时,它破坏了网站,因为网站的其余部分是基于 960 像素的布局.

i have an image that is 1260px wide on my website and when i look at it on the phone it destorts the website as the rest of the website is based on a 960px layout.

我已经为移动设备制作了 960 像素宽的这些图片,但是我如何在 css 中指定如果它是移动设备,请使用移动优化图片而不是常规网站上的图片.

I have made these images to be now 960px wide for the mobile device but how do i specify in css that if it is a mobile use mobile optimized image instead of the one on the regular website.

所以基本上,如果用户在台式计算机上访问网站,它会显示 1260 像素的图像

So basically if a user goes on the website on a desktop computer it will show the 1260px image

如果他们在移动设备上访问该网站,它将显示 960 像素的图像

and if they visit the website on a mobile it will display the 960px image

大家有什么想法吗?

推荐答案

我不确定你是否想要 JS,如果你想要 CSS3,我决定回答你的问题,试试这个:

Im not sure if you want JS, i decided to answer your question if you want CSS3, try this:

HTML:

<img src="image.jpg"
     data-src-960px="image-960px.jpg"
     data-src-1260px="image-1260px.jpg"
     alt="">

CSS:

 @media (min-device-width:320px) {
        img[data-src-960px] {
            content: attr(data-src-960px, url);
        }
    }

    @media (min-device-width:960px) {
        img[data-src-1260px] {
            content: attr(data-src-1260px, url);
        }
    }

jQuery 版本:

 $(document).ready(function() {

 function imageresize() {
 var contentwidth = $('#content').width();
 if ((contentwidth) < '960'){
 $('.imageclass').attr('src','image-960px.jpg');
 } else {
 $('.imageclass').attr('src','image-1260px.jpg');
 }
 }

 imageresize();//Activates when document first loads    

 $(window).bind("resize", function(){
 imageresize();
 });

 });

这篇关于如何根据用户是在桌面浏览器还是移动浏览器上访问,在 css 中指定不同的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆