冬天想看雪,卻不在下雪的地方嗎?這個 jQuery 下雪特效能讓你的網頁降起雪花,為頁面增添浪漫氛圍。線上效果可參考作者展示頁面。
<img src="https:///image/a/0ms3ypph.jpg" />
(function($){
$.fn.snow = function(options){
var $flake = $('<div></div>').css({'position': 'absolute', 'top': '-50px'}).html('❄'),
documentHeight = $(document).height(),
documentWidth = $(document).width(),
defaults = {
minSize : 10,
maxSize : 20,
newOn : 1000,
flakeColor : "#FFFFFF"
},
options = $.extend({}, defaults, options);
var interval = setInterval( function(){
var startPositionLeft = Math.random() * documentWidth - 100,
startOpacity = 0.5 + Math.random(),
sizeFlake = options.minSize + Math.random() * options.maxSize,
endPositionTop = documentHeight - 40,
endPositionLeft = startPositionLeft - 100 + Math.random() * 500,
durationFall = documentHeight * 10 + Math.random() * 5000;
$flake.clone().appendTo('body').css({
left: startPositionLeft,
opacity: startOpacity,
'font-size': sizeFlake,
color: options.flakeColor
}).animate({
top: endPositionTop,
left: endPositionLeft,
opacity: 0.2
},durationFall,'linear',function(){
$(this).remove()
});
}, options.newOn);
};}(jQuery));
$(function(){
$.fn.snow({
minSize: 5,
maxSize: 50,
newOn: 300
});
});
這個特效的做法很優雅:先準備一片「雪花模板」(一個含雪花符號 ❄ 的 div),再用 setInterval 定時複製它、灑到頁面上。每一片雪花出發時,水平位置、透明度、大小都由 Math.random() 隨機決定,因此不會長得一模一樣;接著用 animate() 讓它邊往下落、邊橫向飄移、邊變淡,落下過程的時間也隨機,營造出自然的飄雪感。動畫結束後 remove() 清掉雪花,避免 DOM 無限累積。透過 newOn 參數(數值越小、雪花越密)就能調整雪勢大小。