【发布时间】:2019-08-14 01:06:57
【问题描述】:
我需要一种方法来更改 SVG 内部的图像宽度和高度,基于设备的方向,使用 Javascript(或 SVG 内部的 ECMAScript)。
我正在使用此代码,但它不会影响 SVG 中的图像元素。
// SVG code, inside XHTML file
<svg xmlns="http://www.w3.org/2000/svg" class="birds" height="569px" id="bird01" version="1.1" width="368px" x="0px" xml:space="preserve" xmlns:xlink="http://www.w3.org/1999/xlink" y="0px">
<g>
<defs>
<rect class="crop" height="569" id="SVGID_1_" width="368"></rect>
</defs>
<use overflow="visible" xlink:href="#SVGID_1_"></use>
<g clip-path="url(#SVGID_2_)">
<image clip-path="url(#SVGID_2_)" height="846" id="bird-img" overflow="visible" width="547" xlink:href="../Images/bird.jpeg"></image>
</g>
</g>
</svg>
// JS code, outside file, referenced in head
window.onload = function initialLoad() {
detectOrientation();
}
detectOrientation();
window.onorientationchange = detectOrientation;
function detectOrientation(){
if(typeof window.onorientationchange != 'undefined'){
if ( orientation == 0 ) {
document.getElementById("bird-img").setAttribute("width", "547").setAttribute("height", "846");
}
else if ( orientation == 90 ) {
document.getElementById("bird-img").setAttribute("width", "368").setAttribute("height", "568");
}
else if ( orientation == -90 ) {
document.getElementById("bird-img").setAttribute("width", "368").setAttribute("height", "568");
}
else if ( orientation == 180 ) {
document.getElementById("bird-img").setAttribute("width", "547").setAttribute("height", "846");
}
}
}
此链接显示一个测试页面:http://bit.ly/mSBDhq 调整窗口大小以查看 SVG 框的大小变化。我只想在两种情况下(横向和纵向)将图像大小调整为 SVG 框的宽度。我使用 CSS 媒体查询来完成大部分工作,但 SVG 图像元素不受 CSS 影响,这就是我正在寻找 JS 解决方案的原因。我很欣赏这方面的任何亮点。
旁注:不幸的是,在这种情况下,我根本无法使用常规的图像标签和 CSS 属性溢出结合媒体查询来实现这种效果(长话短说)。
【问题讨论】:
-
在调用函数之前声明函数有帮助吗?
-
你能澄清发生了什么吗?
detectOrientation被叫到了吗?您是否进入了正确的 if 语句分支? (顺便说一句,为了简洁起见,您可能想在这里使用switch。)getElementById返回正确的对象吗?设置属性后,它们是否发生了变化(在 DOM 中),但您在屏幕上看不到任何效果? -
Phrogz 的回答有助于解决一些问题,但即使在此之后元素不受影响......也许 js 无法到达 svg 内部。
标签: javascript ipad svg orientation