萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> CMS 教學

DEDECMS 內容頁圖片過大導致版面錯亂?等比例縮放完美解決

問題背景

文章內容圖片尺寸過大會撐破版面,若強制固定寬高縮放會導致圖片變形。我們需要一種「超寬才縮放、且保持原始比例」的方案。

核心思路

  1. 後端(PHP)在輸出內容時,為每個 <img> 標籤注入 onload="ImgReSize(this)" 事件,並移除 height 屬性,只保留瀏覽器自動計算的高度。
  2. 前端(JS)在圖片載入完成後,檢測實際寬度是否超過容器限制(如 600px),超過則將寬度設為限制值,高度自動等比縮放。

實作步驟

步驟 1:修改核心類文件

打開 include/arc.archives.class.php,找到:

//設置全局環境變量
$this->Fields['typename'] = $this->TypeLink->TypeInfos['typename'];
@SetSysEnv($this->Fields['typeid'],$this->Fields['typename'],$this->Fields['id'],$this->Fields['title'],'archives');

在其下方插入以下代碼:

// 替換圖片 Alt 為文檔標題
$this->Fields['body'] = str_ireplace(array('alt=""', "alt=''"), '', $this->Fields['body']);
$this->Fields['body'] = preg_replace("@[\s]{0,}alt[\s]{0,}=[\"'\s]{0,}[\s\S]{0,}[\"'\s]@isU", " ", $this->Fields['body']);
$this->Fields['body'] = str_ireplace("\"".$this-Fields['title']."\"", $this->Fields['body']);

// 為 img 標籤注入 JS 縮放調用
$suolue = 'onload="javascript:ImgReSize(this)"';
$this->Fields['body'] = str_ireplace("Fields['body']);

// 移除 height 屬性,讓瀏覽器自動等比計算
$this->Fields['body'] = preg_replace('//i', "", $this->Fields['body']);

步驟 2:前台模板加入 JS 函數

打開前台文章頁模板(預設 /templets/default/article_article.htm),在 </body> 前加入:

<script language='javascript'>
function ImgReSize(e) {
  if (e.width > 600) {          // 600 為容器最大寬度,可依版面調整
    e.width = 600;
    e.style.width = "";
  }
  if (e.height > 10) {
    e.style.height = "";
  }
}
</script>

效果驗證

更新文章 HTML 後,內容頁圖片若寬度超過 600px 將自動等比縮小至 600px,高度隨之縮放,版面不再錯亂,圖片也不會變形。

copyright © 萬盛學電腦網 all rights reserved