首页 > 解决方案 > 碰到标志 Div 时缩放 SVG

问题描述

我们有一个 SVG 波浪设计,出现在 WordPress 网站的导航下方。SVG 目前是浮动的,并且希望 SVG 在到达徽标所在的 div 时开始随着浏览器缩小。本质上,我们希望 SVG 覆盖导航中的所有内容,但从不覆盖徽标,即使在缩小。这甚至可能吗?

有关实时示例和代码,请参见http://dev-wisco-radio.pantheonsite.io/

标签: htmlcsswordpresssvgsass

解决方案


除了使用百分比宽度或针对屏幕尺寸变化的媒体查询来近似效果之外,我无法使用纯 CSS 找到解决方案。然而,这完全可以通过 Javascript 根据屏幕和徽标宽度调整 SVG 大小来实现。这是基于您当前的 HTML 和 CSS 使用 JS 的快速实现:

var wave = document.getElementsByClassName("homepage-svg")[0];
var logo = document.getElementsByClassName("site-branding")[0];

window.addEventListener('resize', function(event){
    var screenWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; //Support for different browsers
    var logoWidth = logo.offsetWidth;

    var maxSVGWidth = 1200; //1200px was obtained from your CSS

    //If the screen is too small to show both the wave and the logo at full size (with no overlap), decrease the width of the wave
    if(screenWidth < maxSVGWidth + logoWidth) {
        wave.style.width = screenWidth - logoWidth + "px";
    }
});

我在您共享的链接(在 Chrome 中)上对此进行了测试,它可以正常工作,但是非常粗糙并且不考虑初始页面加载,因为它仅在调整窗口大小时运行。但是,进行任何必要的调整应该相当容易。

希望这可以帮助!:)


推荐阅读