Svelte中SVG背景图无法缩放问题求助
Svelte中SVG背景图无法缩放问题求助
我现在碰到一个头疼的问题:我有一个外层容器,里面套着一个div,这个div里有好几个<p>元素。容器的背景是一张SVG图,它的上下边缘是波浪形状的,所以绝对不能被裁剪。
我试着写了一段JS代码,想自动缩放这个SVG,实现两个效果:一是横向铺满整个屏幕,二是纵向拉伸到能完全装下所有文本。这段代码我放在了OnMount函数里,具体如下:
function updateScale() { const paraContainer = document.getElementById('introPara'); const style = window.getComputedStyle(paraContainer, "::before"); const backgroundImage = style.backgroundImage; let imageUrl = backgroundImage.slice(5, -2); let imgHeight = 0; let imgWidth = 0; const img = new Image(); img.onload = function () { imgHeight = img.height; imgWidth = img.width; const containerHeight = paraContainer.offsetHeight; const containerWidth = paraContainer.offsetWidth; const scaleX = (containerWidth / imgWidth) * 2; const scaleY = (containerHeight / imgHeight) * 1.2; paraContainer.style.backgroundSize = `${scaleX * 100}% ${scaleY * 100}%`; }; img.src = imageUrl; } window.addEventListener('resize', updateScale); updateScale();
对应的CSS样式是这样写的:
.intro-para { color: white !important; padding: 2vw 5vw 2vw 5vw !important; width: 100vw !important; max-width: 100% !important; position: relative; display: flex; align-items: center; justify-content: center; overflow-x: clip; } #introPara::before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-image: url('../../static/SVG/Asset 8 pink.svg#svgView(preserveAspectRatio(none))'); background-size: contain; background-position: center; background-repeat: no-repeat; z-index: -1; }
HTML结构是这样的:
<div class="container intro-para" id="introPara"> <div class="para-content" id="textContainer"> <p>Text</p> <p>Text</p> <p>Text</p> <p>Text</p> </div> </div>
可是现在不管用,这段代码完全起不到缩放背景图的作用,甚至我在开发者工具里手动修改background-size的百分比数值,背景图也没有任何变化。有没有大佬能帮我找找问题出在哪?感激不尽!
备注:内容来源于stack exchange,提问作者tobyallwood
相关产品推荐
相关产品推荐

