Google Map InfoWindow预定义尺寸图片无法正常显示求助
解决Google Maps InfoWindow中图片尺寸限制不生效的问题
我之前也碰到过Google Maps InfoWindow里图片样式不生效的坑,主要是因为InfoWindow的DOM是Google动态生成的,内置的CSS会干扰我们自定义的样式,加上你还不小心写错了一个属性(height-max应该是max-height),难怪设置没生效。给你几个靠谱的解决办法:
方案一:用!important强制提升样式优先级
直接修改图片的内联样式,通过!important来覆盖Google Maps的内置CSS,同时修正属性拼写错误:
const html = ` <img style="max-width: 600px !important; max-height: 100% !important;" src="http://www.oursteps.com.au/bbs/data/attachment/forum/201610/18/023201oqdnhzhnujp9dqzh.jpg" /> <img style="max-width: 600px !important; max-height: 100% !important;" src="http://www.oursteps.com.au/bbs/data/attachment/forum/201610/18/051237g63nvqynyu6lqn6n.jpg" /> <img style="max-width: 600px !important; max-height: 100% !important;" src="http://www.oursteps.com.au/bbs/data/attachment/forum/201610/22/051804s8uoft49zcs79cvv.jpg" /> <img style="max-width: 600px !important; max-height: 100% !important;" src="http://www.oursteps.com.au/bbs/data/attachment/forum/201610/22/051805bbrz99olo9q755lv.jpg" /> `; marker['infowindow'] = new google.maps.InfoWindow({ content: html });
方案二:用容器包裹图片实现自适应
给所有图片套一个宽度100%的容器,让图片自适应容器宽度,而容器会被InfoWindow的宽度限制住:
const html = ` <div style="width: 100%;"> <img style="width: 100%; max-height: 100%;" src="http://www.oursteps.com.au/bbs/data/attachment/forum/201610/18/023201oqdnhzhnujp9dqzh.jpg" /> <img style="width: 100%; max-height: 100%;" src="http://www.oursteps.com.au/bbs/data/attachment/forum/201610/18/051237g63nvqynyu6lqn6n.jpg" /> <img style="width: 100%; max-height: 100%;" src="http://www.oursteps.com.au/bbs/data/attachment/forum/201610/22/051804s8uoft49zcs79cvv.jpg" /> <img style="width: 100%; max-height: 100%;" src="http://www.oursteps.com.au/bbs/data/attachment/forum/201610/22/051805bbrz99olo9q755lv.jpg" /> </div> `; marker['infowindow'] = new google.maps.InfoWindow({ content: html });
这种方式更灵活,哪怕后续调整InfoWindow的宽度,图片也会自动适配。
方案三:自定义CSS类控制样式
如果需要批量控制样式,可以定义全局CSS类,然后给图片添加类名:
首先在页面的CSS中添加:
.info-window-img { max-width: 600px !important; max-height: 100% !important; }
然后修改HTML内容:
const html = ` <img class="info-window-img" src="http://www.oursteps.com.au/bbs/data/attachment/forum/201610/18/023201oqdnhzhnujp9dqzh.jpg" /> <img class="info-window-img" src="http://www.oursteps.com.au/bbs/data/attachment/forum/201610/18/051237g63nvqynyu6lqn6n.jpg" /> <img class="info-window-img" src="http://www.oursteps.com.au/bbs/data/attachment/forum/201610/22/051804s8uoft49zcs79cvv.jpg" /> <img class="info-window-img" src="http://www.oursteps.com.au/bbs/data/attachment/forum/201610/22/051805bbrz99olo9q755lv.jpg" /> `; marker['infowindow'] = new google.maps.InfoWindow({ content: html });
另外提醒一下:InfoWindow的默认最大宽度其实就是600px,所以方案二中用width:100%的容器会自动适配这个宽度,不需要硬写600px,这样代码更通用。
内容的提问来源于stack exchange,提问作者showmyroutes
相关产品推荐
相关产品推荐

