如何使用HTML、CSS和JavaScript建立視差效果?
在本文中,我們將學習視差效果以及如何使用HTML、CSS和JavaScript建立它們。我們將使用滑鼠移動事件來顯示視差效果。在視差效果期間,兩張不同的影像會並排移動。兩張影像將並行工作並進行相同的轉換。唯一的區別在於它們朝相反的方向移動。
視差效果用於改善網站的使用者體驗並增強網站的互動性。我們可以以不同的速度和不同的方向移動前景和背景影像。視差效果可以有多種組合,例如移動文字和影像或影像和影像。
示例
在下面的示例中,我們使用兩張影像實現了視差效果。兩張影像以相同的速度朝相反的方向移動。
#檔名: index.html
<!DOCTYPE html>
<html lang="en">
<head>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: sans-serif;
}
body {
background-color: lightgrey;
}
.mouse_move {
position: relative;
width: 100%;
height: 100vh;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
}
.mouse_move h2 {
position: relative;
font-size: 40px;
color: black;
}
.mouse_move img {
position: absolute;
}
#img1 {
top: 80px;
left: 80px;
height: 250px;
width: 250px;
}
#img2 {
bottom: 80px;
right: 80px;
height: 250px;
width: 250px;
}
</style>
<title>Parallax Effect</title>
</head>
<body>
<div class="mouse_move">
<img
id="img1"
src="https://tutorialspoint.tw/assets/questions/media/64678/5.png"
class="mouse"
value="7"/>
<h2>Welcome To Tutorials Point</h2>
<img
id="img2" src="https://tutorialspoint.tw/images/logo.png" class="mouse" value="-7"/>
</div>
<script type="text/javascript">
document.addEventListener("mousemove", parallax);
function parallax(event) {
this.querySelectorAll(".mouse").forEach((shift) => {
const position = shift.getAttribute("value");
const x = (window.innerWidth - event.pageX * position) / 90;
const y = (window.innerHeight - event.pageY * position) / 90;
shift.style.transform = `translateX(${x}px) translateY(${y}px)`;
});
}
</script>
</body>
</html>輸出

廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP