CSS 轉換:背景大小不起作用-PHP中文網路問答
CSS 轉換:背景大小不起作用
P粉821808309
P粉821808309 2023-09-05 00:05:08
0
1
484

我正在開發一個網站,當您將滑鼠懸停在圖像上時,它會縮小,以便您可以看到整個圖像,而無需縮小太多以查看 div 的背景。

這就是我的 HTML 的樣子:

MALEV Cessna c172 HA-SJX (G1000)

Download

還有我的 CSS:

:root { --img-size: 350px; --button-margin: 20px; --dark-blue: #070b21; --blue: #10184a; --light-blue: #00d1ff; } div#wrapper { position: relative; margin: auto; margin-bottom: 100px; background-color: var(--dark-blue); width: var(--img-size); } div#imgDiv { position: relative; text-align: center; color: red; padding: 0; margin: 0; background-color: var(--dark-blue); overflow: hidden; height: var(--img-size); } div#imgDiv div#transitionDiv { background-position-x: 50%; height: 100%; width: 100%; background-size: auto var(--img-size); background-repeat: no-repeat; -webkit-transition: background-size 1500ms ease; -moz-transition: background-size 1500 ease; -o-transition: background-size 1500 ease; -ms-transition: background-size 1500ms ease; transition: background-size 1500ms ease; } div#imgDiv:hover div#transitionDiv { background-position-y: 50%; background-size: var(--img-size) auto; } p#title { overflow: hidden; height: 38px; margin: 30px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; } div#designs div a { display: block; text-align: center; text-decoration: none; background-color: var(--light-blue); color: white; font-size: 40px; font-family: "Montserrat", sans-serif; margin: var(--button-margin); padding: 0px; width: calc(100% - 2 * var(--button-margin)); border-radius: 15px; transition: 0.5s; } div#designs div a#no-link { background-color: grey; } div#designs div a:hover { background-color: dodgerblue; /* using random color for now */ } div#designs div a:active { background-color: blue; /* using random color for now */ } 

我嘗試尋找解決方案,他們都說按照我的方式去做。這會將背景圖像縮放到正確的大小,但過渡不起作用。

我還嘗試更改 div,使其在 div 內有圖像標籤,但這也不起作用。

P粉821808309
P粉821808309

全部回覆 (1)
P粉156983446

事實證明,過渡不適用於自動和其他一些屬性(覆蓋、包含、繼承、初始、未設定)。我找到的解決方案是使用 JavaScript 使用以下程式碼:

img.onload = function () { let height = img.naturalHeight; let width = img.naturalWidth; let ratio = height / width; img.surroundingDiv.bgSize = "" + ((1 / ratio) * 100) + "%"; img.surroundingDiv.style.backgroundSize = this.surroundingDiv.bgSize; }; transitionDiv.style.backgroundImage = "url(" + img.src + ")"; transitionDiv.onmouseenter = function () { this.style.backgroundSize = 100 + "%"; }; transitionDiv.onmouseleave = function () { this.style.backgroundSize = this.bgSize; };

首先,我計算比率,以計算出當圖像未懸停在其上方時要縮放圖像多少。我必須透過在div中建立一個新屬性bgSize並將其儲存在那裡,來儲存要在onmouseleave事件中使用的該值。

然後,我使用onmouseenteronmouseleave事件來更改懸停在映像上時的圖片大小。

我還刪除了 css 檔案中的:hover選擇器,因為它現在已過時。

    最新下載
    更多>
    網站特效
    網站源碼
    網站素材
    前端模板
    關於我們 免責聲明 Sitemap
    PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!