简体   繁体   English

如何基于屏幕而不是img大小在svg中使用CSS媒体查询?

[英]How to use css media queries in svg based on screen not img size?

I have an svg for a cart icon and am able to style it with css. 我有一个购物车图标的svg,并能够使用CSS对其进行样式设置。 I would like to change the color of the cart based on window size. 我想根据窗口大小更改购物车的颜色。 The problem is @media reads the size of the image to test the media query rather than the window. 问题是@media读取图像的大小以测试媒体查询而不是窗口。

<defs>
    <style type="text/css">
        @media screen and (min-width: 1000px) {
            #Mobile {
                fill: #fff;
            }
        }
    </style>
</defs>

The size of the image is 40 x 40px. 图片大小为40 x 40像素。 Since the size of the image is set to remain constant the media query never becomes active. 由于将图像的大小设置为保持恒定,因此媒体查询永远不会变为活动状态。 Is there a way to make this bypass image size and read screen width like a normal media query? 有没有办法像普通媒体查询一样,使此旁路图像大小和读取屏幕宽度变大?

I'm calling the svg in my html like this: 我在html中这样调用svg:

<object id="cartIcon" type="image/svg+xml" data="Assets/icon-shopping-cart.svg"></object>

I would apply the style via JS and use clientWidth and clientHeight to do the detection. 我将通过JS应用样式,并使用clientWidthclientHeight进行检测。

var width = document.documentElement.clientWidth;
var height = document.documentElement.clientHeight;

if ( width === 456 || height === 123) {
  var element = document.getElementById("Mobile");
  element.style.fill = "white"; 
}

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

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