鼠标移入图片变成碎片/移出图片复原动画效果

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_39872588/article/details/80209244


图片外面只需要一个包裹的div

<div class="box"></div>
.box{
	width: 640px;
	height: 640px;
	margin: 0 auto;
	margin-top: 100px;
	position: relative;
}
.item{
	width: 64px;
	height: 64px;
	position: absolute;
	background-repeat: no-repeat;
	background-image:url(images/dog1.jpg); 
	transition: all 2s;
}

首先引入jQuery.js

JS代码如下

for (var i = 0; i < 100; i++) {
	//创建100个碎片
    $('.box').append('<div class="item"></div>');
    //x偏移
    var x = i % 10;
    //y偏移
    var y = parseInt(i / 10);
    //设置css样式,使用背景图定位属性,让所有图片拼接成一个完整的图片
    $('.item').eq(i).css({
        "background-position": x * (-64) + "px " + y * (-64) + "px",
        "left": x * 64 + "px",
        "top": y * 64 + "px"
    });
}
//图片显示
function imgShow() {

    $('.item').each(function(index, el) {
        var num_x = index % 10;
        var num_y = parseInt(index / 10);
        $(this).css({
            left: num_x * 64 + "px",
            top: num_y * 64 + "px",
            transform: "scale(1)",//图片缩放
            transform: "rotate(0)",//图片旋转
            opacity: 1
        });
    });
}
//图片消失
function imgHide() {
    $('.item').each(function(index, el) {
    	//设置图片消失x轴/y轴的消失范围 [-1000,+1000]
        var num_x = Math.random() * 2000 - 1000;
        var num_y = Math.random() * 2000 - 1000;
        $(this).css({
            left: num_x + "px",
            top: num_y + "px",
            transform: "scale(0.1)",
            transform: "rotate(" + index + "deg)",
            opacity: 0
        });
    });
}
$(".box").hover(function() {
    imgHide();
}, function() {
    imgShow();
});
注意,这里图片的大小必须计算,或者均分.建议测试的时候选择一张正方形的图片. 本demo选取的图片大小是640*640


猜你喜欢

转载自blog.csdn.net/weixin_39872588/article/details/80209244
今日推荐