使用 JavaScript 淡入影象

  1. 使用 className 屬性淡入影象
  2. 使用 requestAnimationFrame() 方法淡入影象
使用 JavaScript 淡入影象

如果沒有 JavaScript,可以使用 CSS 評估影象的淡入樣式。但是這個過程並不可靠,因為我們無法動態處理它。

因此,JavaScript 使用方法 requestAnimationFrame() 而不是完全依賴 CSS 和 setTimeout() 方法的方式使路徑更加快捷和迅速。在示例片段中,我們將看到一個程式碼例項,其中包括方法 requestAnimationFrame() 的實現以及可以在引用屬性 className 的影象中淡入淡出的程式碼。

使用 className 屬性淡入影象

我們將生成一個帶有可行的 srcimg 標籤。存在可點選事件以啟動影象的淡入。這裡的主要工作是使用 className 屬性,該屬性將引用某個 CSS 塊並將其與 img id 例項對齊。

程式碼 - HTML 檔案:

<img id="img" style="width: 200px" src="https://images.unsplash.com/photo-1653450283266-c788c2ca4ab2?ixlib=rb-1.2.1&raw_url=true&q=80&fm=jpg&crop=entropy&cs=tinysrgb&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=872" alt="Image 1">
<br><br>
<button type="button" onclick="myFunction()">Change</button>

程式碼 - CSS 檔案:

img {
            opacity: 0;
            filter: alpha(opacity=40);
    }
.animation {
            -webkit-transition: 1s;
            -moz-transition: 1s;
            -o-transition: 1s;
            transition: 1s;
            opacity: 1;
        }

程式碼 - JavaScript 檔案:

function myFunction() {
  document.getElementById('img').className = 'animation';
}

輸出:

使用 className 屬性淡入影象

使用 requestAnimationFrame() 方法淡入影象

在這方面,我們將有一個函式 fadeIn,它將採用 img 標籤的例項。稍後,fadeIn 函式將對 requestAnimationFrame()setTimeout() 進行操作,並根據當前瀏覽器詳細資訊定位時間範圍。

程式碼 - HTML 檔案:

<img id="what" src="https://images.unsplash.com/photo-1653372500616-ff0a2847f7ca?crop=entropy&cs=tinysrgb&fm=jpg&ixlib=rb-1.2.1&q=80&raw_url=true&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=774" draggable="true" ondragstart="drag(event)" width="200" height="150">
<br><br>
<button onclick="myFunction()">Change</button>

程式碼 - CSS 檔案:

img {
    opacity: 0;
    filter: alpha(opacity=40);
}

程式碼 - JavaScript 檔案:

function fadeIn(el) {
  el.style.opacity = 0;
  var tick = function() {
    el.style.opacity = +el.style.opacity + 0.05;
    if (+el.style.opacity < 1) {
      var x = (window.requestAnimationFrame && requestAnimationFrame(tick)) ||
          setTimeout(tick, 16)
    }
  };
  tick();
}

function myFunction() {
  var el = document.getElementById('what');
  console.log(el);
  fadeIn(el);
}

輸出:

使用 requestAnimationFrame() 方法淡入影象

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Anika Tabassum Era avatar Anika Tabassum Era avatar

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

LinkedIn Facebook

相關文章 - JavaScript Image