当视口小于600像素时,我正在尝试旋转SVG中制作的图形。我使用了媒体查询器,但效果很好,但是svg从它的容器中溢出了,无论我做什么,我都无法修复。
是否可以在不使用javascript的情况下进行修复?
我尝试使用prepareAspectRatio属性和viewbox属性,但是它不起作用。
这是代码:https://codepen.io/telumire-the-sasster/pen/vYBxLRg
HTML:
<div class="container">
<svg viewBox="0 0 700 100" preserveAspectRatio="none" class="graphic" style="">
<polyline fill="red" stroke="none"
points="
0,0
0,15
100,14
200,18
300,21
400,23
500,22
600,17
700,17
700,0
0,0
"/>
</svg>
</div>
CSS:
.container {
background-color: green;
}
.graphic {
transform: scaleY(-1);
}
@media (max-width: 599px) {
/* smartphone */
.graphic {
transform: rotate(90deg);
height: 100%;
display: block;
}
}
我希望svg不会从绿色容器中溢出(它必须适合其高度)。
答案 0 :(得分:0)
svg的高度不超过容器的高度。问题是您将svg旋转90度,以便在视觉上它的宽度变成它的高度,但是在视觉上,因为它仍然算作宽度。
编辑: 添加了jQuery解决方案。使用此设置,如果视口小于600,则svg会像以前一样旋转,但是JavaScript会将height值替换为width值,并将width值替换为height值。这是代码:
$(window).resize(function() {
if ($(window).width() <= 600) {
var h = $('#svg').height();
var w = $('#svg').width();
$('#svg').attr('width', h);
$('#svg').attr('height', w);
}
});
.container {
background-color: green;
}
.graphic {
transform: scaleY(-1);
}
@media (max-width: 599px) {
/* smartphone */
.container {
height: 200px;
}
.graphic {
transform: rotate(90deg);
height: 100%;
display: block;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<svg viewBox="0 0 700 100" preserveAspectRatio="none" class="graphic" style="" id="svg">
<polyline fill="red" stroke="none" points="
0,0
0,15
100,14
200,18
300,21
400,23
500,22
600,17
700,17
700,0
0,0
" />
</svg>
</div>
其他选择是放置2个svg(一个垂直对齐,一个水平对齐),一次只显示其中一个。
答案 1 :(得分:0)
对于任何有兴趣的人,我最终都选择使用2个嵌入式svg:
HTML:
<div class="container">
<svg
viewBox="0 0 700 100"
preserveAspectRatio="none"
class="graphic landscape"
>
<!-- <g transform="translate(0,100)"></g><g transform="scale(1,-1)"></g> -->
<polyline
fill="lightgrey"
stroke="none"
points="
0,0
0,60
100,56
200,72
300,84
400,92
500,88
600,68
700,68
700,0
"
/>
</svg>
<svg
viewBox="0 0 100 700"
preserveAspectRatio="none"
class="graphic portrait"
>
<!-- <g transform=" translate(0,100) "></g><g transform="scale(1,-1) "></g> -->
<polyline
fill="lightgrey "
stroke="none "
points="
0,0
60,0
56,100
72,200
84,300
92,400
88,500
68,600
68,700
0,700
"
/>
</svg>
</div>
CSS:
.container {
background-color: green;
height: 50vh;
}
.graphic {
transform: scaleY(-1);
overflow-x: hidden;
overflow-y: hidden;
}
.landscape {
display: block;
width: 100%;
/* max-height: 100%; */
height: 100%;
}
.portrait {
display: none;
height: 100%;
/* max-width: 100%; */
width: 100%;
}
@media (max-width: 599px) {
/* smartphone */
.portrait {
display: block;
}
.landscape {
display: none;
}
}
下一步是使用js来自动化第二张图的坐标
编辑:您实际上应该在此处使用display: none;
和display: block;
,因为visibility: hidden;
和visibility: visible;
也不显示标签,但会为它,我们希望避免这种情况。