DIV CSS 佈局教程網

用 JS 隱藏 iframe 的捲軸
編輯:關於JavaScript     

iframe 預設會依內容自動顯示捲軸,但我們常常希望把它藏起來,讓內嵌頁面看起來像主頁面的一部分。scrolling 屬性就是為此而生。

 <!DOCTYPE html>
<html>
<head>
<script>
function removeScroll() {
  document.getElementById("myframe").scrolling = "no";
}
</script>
</head>
<body>
<iframe id="myframe" src="/default.asp" scrolling="auto">
  <p>Your browser does not support iframes.</p>
</iframe>
<p>The value of the scrolling attribute is:
<script>
 document.write(document.getElementById("myframe").scrolling);
</script>
</p>
<input type="button" onclick="removeScroll()" value="Remove Scrollbars" />
<p>Internet Explorer, Google Chrome, Opera, and Safari have problems
with setting the scrolling attribute.</p>
</body>
</html>

scrolling 的三個值

· yes 永遠顯示捲軸
· no 永不顯示
· auto 內容超出時才顯示(預設)

這個屬性在 HTML5 中已被棄用,瀏覽器對以 JavaScript 動態設定的支援也不一致(正如範例註解所述)。

改用 CSS overflow

標準做法是在 iframe 內部頁面上控制 overflow。若你能編輯內嵌頁:

 /* iframe 內部頁面的樣式 */
html, body {
  overflow: hidden;   /* 完全隱藏 */
  /* 或 overflow-y: auto; 只在需要時顯示 */
}

若無法編輯內嵌頁,且兩者同源,可以從父頁面注入:

 var frame = document.getElementById("myframe");

 frame.addEventListener('load', function() {
   try {
     var doc = frame.contentDocument;
     doc.documentElement.style.overflow = "hidden";
     doc.body.style.overflow = "hidden";
   } catch (e) {
     console.warn('跨來源,無法修改內部樣式');
   }
 });

跨來源時怎麼辦

同源政策會擋下上述做法。此時只剩兩條路:

· 請對方在其頁面加上能接受查詢參數的樣式開關,或透過 postMessage 通知它自行隱藏。
· 在父頁面的 iframe 外層包一個固定高度的容器,用負的 margin 把捲軸推出視線——這是變通手法,副作用多,不推薦。

先想清楚:你真的該隱藏捲軸嗎

隱藏捲軸是個有爭議的決定。捲軸同時也是「這裡還有更多內容」的視覺提示,藏起來之後,使用者可能不知道頁面可以往下捲,造成內容被忽略。無障礙上也有疑慮——鍵盤使用者失去明確的位置參考。

更好的替代方案:

· 若內容是自家頁面,讓 iframe 高度自適應內容,就不需要捲軸了(同源時可讀 scrollHeight,跨來源則需對方以 postMessage 回報高度)。
· 若內容本質上較長,改用 overflow-y: auto 保留捲動能力,只是讓捲軸在不用時自動消失。
· 若只是視覺上不喜歡系統捲軸樣式,用 CSS 客製化(::-webkit-scrollbar 或標準的 scrollbar-width/scrollbar-color)會比直接隱藏好得多。

結論:技术上隱藏捲軸很容易,但請先確認使用者仍然知道該如何取得完整內容。

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