頁面右側固定懸浮 QQ 客服圖示,滾動頁面時平滑跟隨視窗垂直置中;滑鼠移入展開客服列表,移出收合。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>QQ 客服懸浮效果</title>
<style>
.qq-float {
position: fixed; right: 0; z-index: 9999;
width: 36px; height: 128px;
background: url('images/qq_tab.png') no-repeat;
cursor: pointer;
transition: width 0.3s;
}
.qq-float.expanded { width: 160px; }
.qq-list { display: none; padding: 10px; background: #fff; border: 1px solid #ddd; }
.qq-float.expanded .qq-list { display: block; }
.qq-list li { margin: 8px 0; }
.qq-list img { vertical-align: middle; margin-right: 6px; }
</style>
</head>
<body style="height: 3000px;">
<div class="qq-float" id="qqFloat">
<div class="qq-list">
<ul>
<li><a href="tencent://message/?uin=123456"><img src="images/qq_icon.gif">客服 1</a></li>
<li><a href="tencent://message/?uin=234567"><img src="images/qq_icon.gif">客服 2</a></li>
</ul>
</div>
</div>
<script>
(function() {
var $box = $('#qqFloat');
var $list = $box.find('.qq-list');
var winH = $(window).height();
var boxH = $box.outerHeight();
var targetTop = (winH - boxH) / 2;
var timer = null;
// 平滑跟隨滾動
function followScroll() {
var scrollTop = $(window).scrollTop();
var dest = scrollTop + targetTop;
clearInterval(timer);
timer = setInterval(function() {
var current = $box.offset().top;
var diff = dest - current;
var speed = diff > 0 ? Math.ceil(diff / 8) : Math.floor(diff / 8);
if (diff === 0) { clearInterval(timer); return; }
$box.css('top', current + speed);
}, 30);
}
$(window).on('scroll resize', followScroll);
followScroll(); // 初始定位
// 滑鼠互動
$box.hover(
function() { $box.addClass('expanded'); },
function() { $box.removeClass('expanded'); }
);
})();
</script>
</body>
</html>
position: fixed 脫離文件流,配合 setInterval 緩動演算法 speed = (target - current) / 8 實現平滑跟隨。(windowHeight - boxHeight) / 2 確保垂直居中。transition,JS 僅切換 class。requestAnimationFrame 或 _.throttle。IntersectionObserver 或 position: sticky 替代滾動計算(但 sticky 無法置中)。requestAnimationFrame + transform: translateY() 啟用 GPU。