[英]expand div height onmouseover
我在默認情況下需要div 50px的高度,並且必須在onmouseover上更改為300px。 我用以下方式編寫代碼來實現它。
<style type="text/css">
#div1{
height:50px;
overflow:hidden;
}
#div1:hover{
height:300px;
}
</style>
<body>
<div id="div1"></div>
</body>
這段代碼工作正常但是根據CSS屬性懸停它會立即改變它的高度。 現在,我需要一種時尚的方式,比如慢慢擴大div onmouseover和收縮。 如何在懸停時擴展和收縮div?
有幾種方法 - 這里是CSS和Jquery,它應該適用於所有瀏覽器,而不僅僅是現代瀏覽器:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#div1").hover(
//on mouseover
function() {
$(this).animate({
height: '+=250' //adds 250px
}, 'slow' //sets animation speed to slow
);
},
//on mouseout
function() {
$(this).animate({
height: '-=250px' //substracts 250px
}, 'slow'
);
}
);
});
</script>
<style type="text/css">
#div1{
height:50px;
overflow:hidden;
background: red; /* just for demo */
}
</style>
<body>
<div id="div1">This is div 1</div>
</body>
#div1{
-webkit-transition: all .3s ease-in-out;
-moz-transition: all .3s ease-in-out;
-o-transition: all .3s ease-in-out;
-ms-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
簡單!
在“現代”瀏覽器中,您只需應用css transition effect
:
#div1 {
-moz-transition: 4s all ease-in-out;
-ms-transition: 4s all ease-in-out;
-webkit-transition: 4s all ease-in-out;
-o-transition: 4s all ease-in-out;
}
這將適用的過渡效果超過4秒一個ease-in-out
放寬兼容火狐,IE,鉻/ Safari瀏覽器(WebKit的)和Opera瀏覽器。 閱讀更多:
您可以提前一步檢查當前瀏覽器是否支持css轉換(如果可用),將它們用於動畫,如果不使用javascript動畫腳本。 示例:
您可以使用jQuery的.animate()
這將對任何帶有“tab”類的元素起作用,並將在鼠標移出時恢復。
$('.tab').hover(function() {
$(this).stop()
$(this).animate({
height: '+=250'
}, 500)
}, function() {
$(this).stop()
$(this).animate({
height: '-=250'
}, 500)
})
您可以使用jQuery的.mouseover
http://api.jquery.com/mouseover/ , .mouseout
http://api.jquery.com/mouseout/和.animate
http://api.jquery.com/animate/到執行。
在.mouseover
事件中,您將高度設置為300px,在.mouseout
事件上,您將設置動畫為50px。 確保在調用動畫之前在div上調用.stop
,否則你會遇到奇怪的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.