
今天來看一個商品后臺頁面設計時常用的js效果,圖片彈窗,就是在滑鼠點擊小圖片的時候,會以一個彈窗的形式放大圖片,方便我們查看細節,而且還有很多動效在里面,我們先來看看效果圖:
- 這是滑鼠在圖片外,就是一張小圖,加了一點圓角

- 當滑鼠移到圖片上的時候就會有陰影效果和透明度變化

- 點擊小圖片就是這樣的了,可以查看大圖

設計思路也很簡單,就是先寫出來基本的html和css布局,這里說下×是一個叉號,然后js里面設定兩個點擊事件,每個點擊事件通過方法改變一些元素的css樣式,代碼里的注釋寫的很詳細!
附上原始碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>圖片彈窗</title>
<link rel="stylesheet" href="1.css">
</head>
<body>
<!-- 觸發彈窗 - 圖片為本地的的圖片地址 -->
<img id="myImg" src="img/1.jpg" alt="炸裂得分王-詹姆斯.哈登" width="300" height="200">
<!-- 彈窗 -->
<div id="myModal" class="modal">
<!-- 關閉按鈕,×這個是叉號 -->
<span class="close" onclick="document.getElementById('myModal').style.display='none'">×</span>
<!-- 彈窗內容 -->
<img class="modal-content" id="img01">
<!-- 文本描述 -->
<div id="caption"></div>
</div>
<script src="1.js"></script>
</body>
</html>
/* 觸發彈窗圖片的樣式 */
#myImg {
display: block;
margin: auto;
border-radius: 5px;
/* 游標位于圖片的時候,展示形式是個小手 */
cursor: pointer;
transition: 0.3s;
}
/* img的hover效果,可以設定透明度 */
#myImg:hover {
opacity: 0.85;
box-shadow: 0 8px 12px 0 rgba(0, 0, 0, 0.2)
}
/* 彈窗背景 */
.modal {
display: none;
/* 設定位置,不隨螢屏移動而移動 */
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.5);
}
/* 圖片 */
.modal-content {
border-radius: 10px;
margin: auto;
display: block;
width: 80%;
max-width: 700px;
}
/* 文本內容 */
#caption {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
text-align: center;
color: #aaa;
padding: 10px 0;
height: 150px;
font-size: 1.4rem;
}
/* 添加影片 */
.modal-content,
#caption {
/* 設定影片名 */
-webkit-animation-name: zoom;
-webkit-animation-duration: 0.6s;
animation-name: zoom;
animation-duration: 0.6s;
}
/* 設定影片效果 */
@-webkit-keyframes zoom {
from {
-webkit-transform: scale(0)
}
to {
-webkit-transform: scale(1)
}
}
@keyframes zoom {
from {
transform: scale(0)
}
to {
transform: scale(1)
}
}
/* 關閉按鈕 */
.close {
position: absolute;
top: 15px;
right: 35px;
color: #f1f1f1;
font-size: 40px;
/* 加粗字體 */
font-weight: bold;
transition: 0.3s;
}
.close:hover,
.close:focus {
color: #bbb;
text-decoration: none;
cursor: pointer;
}
/* 小螢屏中圖片寬度為 100%,回應式布局 */
@media only screen and (max-width: 700px) {
.modal-content {
width: 100%;
}
}
// 獲取彈窗
var modal = document.getElementById('myModal');
// 獲取圖片插入到彈窗 ,使用 "alt" 屬性作為文本部分的內容
var img = document.getElementById('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function() {
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
// 獲取 <span>標簽里面的元素,也就是那個叉號,設定關閉按鈕,陣列形式的元素,第一個就是[0]
var span = document.getElementsByClassName("close")[0];
// 當點擊叉號的時候, 關閉彈窗
span.onclick = function() {
modal.style.display = "none";
}
不懂的記得及時評論區或者私信詢問哦!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/229879.html
標籤:其他
上一篇:走向大佬第一步,建構式真武術
下一篇:瀏覽器實作滾動截屏
