您好我尝试获取<g>
元素的宽度,无论如何它总是显示509.5像素。
起初我虽然它是真实的尺寸,但是没有缩放尺寸。
但我在Illustrator中打开了SVG,宽度为700像素。
我在这里制作了一个JSFiddle http://jsfiddle.net/hrsetyono/v51phqww/
任何解决方案?
由于
修改
我在Chrome上尝试过,但它在Firefox中具有相同的行为
答案 0 :(得分:3)
509.5px是它的实际大小,在用户空间(svg文档&#39;)。
如果您删除viewBox
属性并使用插图画家重新打开它,则会为您提供509.5px
的宽度。
现在,如果您希望在窗口(DOM)空间中获取其大小,请使用element.getBoundingClientRect()
。
$(document).ready(function() {
var $screen = $("#screen")[0];
var screenWidth = $screen.getBoundingClientRect().width;
log("width is " + screenWidth);
// try changing the width in CSS and the console always still shows 509.5
});
function log(data){
$('#log').text(data);
}
&#13;
#macbook {
width: 400px;
height: auto;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg id="macbook" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 669.9 387.8">
<g>
<line fill="none" stroke="#939598" stroke-miterlimit="10" x1="546" y1="356.5" x2="548" y2="365.6"/>
<line fill="none" stroke="#939598" stroke-miterlimit="10" x1="122.7" y1="356.5" x2="120.5" y2="365.6"/>
<path fill="none" stroke="#939598" stroke-width="1.5" stroke-miterlimit="10" d="M64.9,365c-0.9-2.2-1.4-4.5-1.4-7l0-337.5
c0-10.4,8.4-18.8,18.8-18.8l505.4,0c10.4,0,18.8,8.4,18.8,18.8l0,337.5c0,2.5-0.5,5-1.4,7.2"/>
<path fill="none" stroke="#939598" stroke-miterlimit="10" d="M586.4,356.5l-502.7,0c-16.8,0-17.1,0-17.1-17.1l0-317.3
C66.5,12.6,74.2,5,83.7,5l502.7,0c9.5,0,17.1,7.7,17.1,17.1l0,317.3C603.5,356.5,603.5,356.5,586.4,356.5z"/>
<g id="screen">
<path fill="#939598" d="M588.3,24.3v320.3H81.8V24.3H588.3 M588.3,22.8H81.8c-0.8,0-1.5,0.7-1.5,1.5v320.3c0,0.8,0.7,1.5,1.5,1.5
h506.5c0.8,0,1.5-0.7,1.5-1.5V24.3C589.8,23.5,589.1,22.8,588.3,22.8L588.3,22.8z"/>
</g>
<circle fill="none" stroke="#939598" stroke-miterlimit="10" cx="335" cy="14.2" r="2.8"/>
<rect x="1.6" y="365.6" fill="none" stroke="#939598" stroke-width="1.5" stroke-linejoin="round" stroke-miterlimit="10" width="666.7" height="11.2"/>
<path fill="none" stroke="#939598" stroke-width="1.5" stroke-miterlimit="10" d="M668.4,376.8c0,0-10.4,9.1-41.4,9.1
c-31,0-584.7,0-597.3,0s-28-9.1-28-9.1"/>
<path fill="#939598" d="M440.8,383.1h-5.3c-0.8,0-1.5-0.7-1.5-1.5l0,0c0-0.8,0.7-1.5,1.5-1.5h5.3c0.8,0,1.5,0.7,1.5,1.5v0
C442.3,382.4,441.7,383.1,440.8,383.1z"/>
<path fill="#939598" d="M233.5,383.1h-5.3c-0.8,0-1.5-0.7-1.5-1.5l0,0c0-0.8,0.7-1.5,1.5-1.5h5.3c0.8,0,1.5,0.7,1.5,1.5l0,0
C235,382.4,234.3,383.1,233.5,383.1z"/>
<path fill="none" stroke="#939598" stroke-miterlimit="10" d="M288.5,365.6c0,0,0.5,6.9,8.7,6.9c8.2,0,69.2,0,76,0
c8,0,8.8-6.9,8.8-6.9"/>
</g>
</svg>
<div id="log"></div>
&#13;