简体   繁体   English

如果屏幕宽度 <= 699,则交换图像 src

[英]Swap image src if screen width <= 699

I have two images "image-big.jpg" and "image-small.jpg" I want to via javascript detect if screen width <= 699 and change the SRC of my image with class="imageswap" from image-big.jpg to image-small.jpg.我有两个图像“image-big.jpg”和“image-small.jpg”我想通过javascript检测屏幕宽度是否<= 699并使用image-big.jpg中的class =“imageswap”更改我的图像的SRC到 image-small.jpg。

So basically if they are on a portable device it will display the smaller image.所以基本上如果它们在便携式设备上,它将显示较小的图像。

I am novice at best with javascsript and any help is gratefully appreciated!我对 javascsript 充其量只是新手,非常感谢任何帮助!

Bind to the window onresize event:绑定到窗口 onresize 事件:

window.onresize = function(event) {
    if(window.innerWidth && window.innerWidth===699)
       document.getElementById('myImg').src = 'newSource';
    else if(document.body.offsetWidth && document.body.offsetWidth===669)
       document.getElementById('myImg').src = 'newSource';
};

The else if is for IE < v.9 else if适用于 IE < v.9

Its no in specs but screen works fine in all browsers.它没有规范,但screen在所有浏览器中都可以正常工作。

if(screen.width <= 699){
   // do you logic
}

1st approach: client-side.第一种方法:客户端。 Set classname to html tag on dom ready after detection device type.检测设备类型后,在 dom 上将 classname 设置为 html 标记。 Use css:使用CSS:

html.big .image-div {background-image:url('big.jpg')}
html.small .image-div {background-image:url('small.jpg')}

2nd approach: redirect.方法二:重定向。 Use 2 different URLs and redirect for small size by detection User-Agent.使用 2 个不同的 URL 并通过检测 User-Agent 重定向小尺寸。 It's better to use User-Agent (navigator object) than window/screen width最好使用 User-Agent(导航器对象)而不是窗口/屏幕宽度

Usually I preffer redirects, because you have better code and page look when you can customize it for specific device.通常我更喜欢重定向,因为当您可以为特定设备自定义它时,您有更好的代码和页面外观。 It's the way how leaders behave.这就是领导者的行为方式。

Try media-query.尝试媒体查询。

.imageswap{
 background-image:url('small.jpg');
}
    @media screen and (max-width: 699px) {
      background-image:url('small.jpg');
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM