Heim > Fragen und Antworten > Hauptteil
**直接上代码,输入‘我想你’我会显示弹出下“心”的效果,并且优化一下代码。
求大神帮忙看下,怎么才能把“心”不重叠?**
html结构:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body{
background: #000;
overflow: hidden;
}
</style>
</head>
<body>
<input type="text" id="txt">
<script src="http://cdn.bootcss.com/jquery/1.12.3/jquery.js"></script>
<script src="snow.js"></script>
<script>
$(document).ready(function() {
$("#txt").on("input",function(){
if($(this).val()=="我想你"){
$.fn.snow({
newOn: 50
});
}
})
});
</script>
</body>
</html>
下面是snow.js
(function($) {
$.fn.snow = function(options) {
var documentHeight = $(document).height(),
documentWidth = $(document).width();
defaults = {
urlImg: "love.png",//img路径
minSize: 20,//控制最小元素
maxSize: 30,//控制最大元素
newOn: 100,//控制显示的多少
speed: 2000,//控制速度
overTime: 5000,//显示多长时间结束
opacity:1,// 透明度
xVlaue:0, // x轴是否发生位移 0:代表不发生位移 1:代表发生位移
rotate:60, // 角度
overlay:true,//是否重叠,默认重叠为true,否则为false
callBack:function(){}
},
options = $.extend({}, defaults, options);
var snowBox=$('<p class="snowBox" />').css({'width':'100%','height':'100%','background':'transparent','position':'absolute','left':0,'top':0,'z-index':99998}).appendTo('body'),
$snow = $('<p class="snow" />').css({ 'position': 'absolute', 'top': '-50px','pointer-events':'none','user-select':'none','z-index':99999}).html('<img src="'+options.urlImg+'" style="width:100%;height:auto">');
var interval = setInterval(function() {
var startPositionLeft = Math.random() * documentWidth - 100,
startOpacity = 0.5 + Math.random(),
sizeFlake = options.minSize + Math.random() * options.maxSize,// 图片的宽度
endPositionTop = documentHeight,
endPositionLeft = startPositionLeft - 100 + Math.random() * 200,
rotateDeg=Math.random() * options.rotate + Math.random() * (-options.rotate);
if(startPositionLeft<10){
startPositionLeft= 30 + Math.random()*10;
}
if(endPositionLeft<10){
endPositionLeft= 30 + Math.random()*100;
}
if(options.xVlaue==0){
endPositionLeft = startPositionLeft;
}else{
endPositionLeft = startPositionLeft - 50 + Math.random() * 200;
};
$snow.clone().appendTo(snowBox).css({
left: startPositionLeft,
opacity: 0.3,
width: sizeFlake+"px",
'-webkit-transform':'rotate('+rotateDeg+'deg)',
'-moz-transform':'rotate('+rotateDeg+'deg)',
'-ms-transform':'rotate('+rotateDeg+'deg)',
'-o-transform':'rotate('+rotateDeg+'deg)',
'transform':'rotate('+rotateDeg+'deg)',
}).animate({
top: endPositionTop,
left: endPositionLeft,
opacity: 1
},
options.speed,
'linear',
function() {
$(this).remove()
}
);
}, options.newOn);
setInterval(function(){
clearInterval(interval);
snowBox.remove();
options.callBack && options.callBack();
},options.overTime);
};
})(jQuery);