點擊內容區域,上方「撕紙」層向左滑動露出底層內容,再次點擊復原。模擬騰訊微博 App 早期的撕紙交互,包含彈性動畫、拖拽手柄、內容雙層疊加。
<div class="container">
<!-- 底層內容(撕開後顯示) -->
<div class="content" id="content">
<div class="content-inner">底層列表內容...</div>
<!-- 撕紙手柄區域 -->
<div class="tear-handle" id="tearHandle">JS 模擬撕紙效果</div>
<!-- 被撕開的上層內容(偽裝在底層上方) -->
<div class="mask" id="mask">
<div class="content-inner" id="maskContent">上層列表內容...</div>
</div>
</div>
</div>
.container {
width: 300px;
height: 400px;
position: relative;
overflow: hidden;
font-size: 12px;
line-height: 20px;
background: #f2eee3;
cursor: pointer;
}
.content {
position: absolute;
top: 0; left: 0;
width: 100%; height: 100%;
overflow: hidden;
}
.mask {
position: absolute;
top: 0; left: 0;
width: 100%; height: 100%;
background: #fff; /* 撕紙背景色 */
overflow: hidden;
/* 初始覆蓋全部內容 */
}
.tear-handle {
position: absolute;
top: 0; left: 0;
width: 100%; height: 50px; /* 手柄高度 */
background: url('tear-texture.gif') no-repeat center;
line-height: 50px;
text-align: center;
cursor: pointer;
z-index: 10;
}
// 簡易緩動動畫框架
var $ = function(id) {
return typeof id === 'string' ? document.getElementById(id) : id;
};
function getStyle(obj, attr) {
return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj, false)[attr];
}
function startMove(obj, json, fnEnd) {
clearInterval(obj.timer);
obj.timer = setInterval(function() {
doMove(obj, json, fnEnd);
}, 10);
}
function doMove(obj, json, fnEnd) {
var bStop = true;
for (var attr in json) {
var iCur = attr === 'opacity'
? parseInt(100 * parseFloat(getStyle(obj, 'opacity')))
: parseInt(getStyle(obj, attr));
if (isNaN(iCur)) iCur = 0;
var iSpeed = (json[attr] - iCur) / 8; // 緩動係數
iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);
if (json[attr] !== iCur) bStop = false;
if (attr === 'opacity') {
obj.style.filter = 'alpha(opacity:' + (iCur + iSpeed) + ')';
obj.style.opacity = (iCur + iSpeed) / 100;
} else {
obj.style[attr] = iCur + iSpeed + 'px';
}
}
if (bStop) {
clearInterval(obj.timer);
obj.timer = null;
if (fnEnd) fnEnd();
}
}
var isTorn = false;
$('content').onclick = function(e) {
e = e || window.event;
var y = e.clientY - 25; // 點擊位置相對容器頂部(扣除手柄一半高度)
y = Math.max(0, Math.min(350, y)); // 限制在可視範圍
if (!isTorn) {
// 撕開:mask 向左滑出,maskContent 向上偏移露出底層對應位置
$('tearHandle').style.top = $('mask').style.top = y + 'px';
$('maskContent').style.top = -y + 'px';
startMove($('mask'), { left: -300 }); // 寬度 300px 完全滑出
isTorn = true;
} else {
// 復原
startMove($('mask'), { left: 0 });
isTorn = false;
}
};
這個撕紙效果展示了早期 Web 交互的創意:通過雙層絕對定位、緩動動畫、座標同步模擬物理行為。雖然代碼風格較老舊,但「狀態機 + 緩動 + 座標映射」的思想在現代動畫庫(GSAP、Framer Motion)中依然通用。