写模态框时,当模态框show的时候动画没有,原来是元素有display:none时添加样式里css3的变幻效果无法生效,解决的方法总结,测试代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
.modal{
z-index: 100;
height: 200px;
width: 200px;
background: yellow;
transition: all 1s;
display:none;
}
.modal.active{
background: red;
transform: translateX(100px);
}
1
2
<a href="javascript:" id="trigger" data-target="#model1">运行动画</a>
<div id="model1" class="modal"></div>

方法一

元素显示后再触发重绘就能让动画生效,读取Layout属性可以触发repaint,这些属性有offsetLeft、offsetTop、offsetHeight、offsetWidth、scrollTop/Left/Width/Height、clientTop/Left/Width/Height、getComputedStyle()等,用jquery的话与这些属性相关的都行。

1
2
3
4
5
6
7
8
9
10
$('#trigger1').click(function () {
var $target = $($(this).data('target'));
if ($target) {
$target.show();
// $target.width();
$target[0].offsetWidth;
$target.addClass('active');
}
});

运行动画

方法二

利用了js的setTimout

1
2
3
4
5
6
7
8
9
$('#trigger2').click(function () {
var $target = $($(this).data('target'));
if ($target) {
$target.show();
setTimeout(function () {
$target.addClass('active');
}, 0);
}
});
运行动画

方法三

用visibility代替display隐藏元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#modal3{
z-index: 100;
height: 200px;
width: 200px;
background: yellow;
transition: all 1s;
visibility:hidden;
position: absolute;
clip:rect(1px, 1px, 1px, 1px);
overflow: hidden;
}
#modal3.active{
position: relative;
clip: auto;
visibility:visible;
background: red;
transform: translateX(100px);
}
1
2
3
4
5
6
7
$('#trigger3').click(function () {
var $target = $($(this).data('target'));
if ($target) {
$target.show();
$target.addClass('active');
}
});
运行动画