DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> XML學習教程 >> XML詳解
用 object 標籤完整顯示 SVG,不被裁掉
編輯:XML詳解     

在 HTML 中嵌入 SVG,<object> 通常比 <embed> 更合適:當 SVG 尺寸超出容器時,<object> 會整體縮放,而 <embed> 往往直接把超出部分裁掉。問題是 <object> 是比較不正式的標籤,相容性沒那麼穩妥。

所以實務上的折衷是:若要給廣大使用者看,用 <embed> 比較保險;但要避免裁切,就得自己先把 SVG 的 width 與 height 讀出來,明確寫進標籤裡。

好消息是 SVG 本身就是 XML,讀取尺寸變得很簡單。

<%@ Import NameSpace="System.XML" %> 別忘了導入相應的名稱空間。

以下函數的作用就不贅述,.NET Framework 文件中都有詳細說明:

sub showSvgWindow(theSvgPath as string)
  dim reader as XMLTextReader = Nothing
  dim nodeAttribute as new ArrayList()
  dim i, width, height as integer
  reader = new XMLTextReader(Server.MapPath(theSvgPath))
  dim exp as Exception
  Try
    While reader.Read()
      If reader.NodeType = XMLNodeType.Element And reader.Name = "svg" Then
        If reader.HasAttributes Then
          For i = 0 to (reader.AttributeCount - 1)
            reader.MoveToAttribute(i)
            If reader.Name = "width" Then width = reader.Value
            If reader.Name = "height" Then height = reader.Value
          Next
        End If
        Exit While
      End If
    End While
  Catch exp
  End Try
  ' 給一個下限,避免尺寸為 0 時看不見
  If CInt(width) < 50 Then width = "50"
  If CInt(height) < 50 Then height = "50"
  svgWindow.Text = "<embed src=" & theSvgPath & " height=" & height _
    & "px width=" & width & "px></embed>"
  svgTitle.Text = Request.QueryString("title")
end sub

幾個實作提醒:SVG 的 width/height 若寫成 "100%" 或帶單位,CInt 轉換會失敗,實務上應該用 Double.TryParse 之類的方式容錯,或改用 viewBox 來推比例。另外 svgTitle 直接取 QueryString 輸出,正式環境請加 Server.HtmlEncode,否則會有 XSS 風險。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved