Danh mục

Thứ Hai, 26 tháng 7, 2010

jQuery - mouse hover

Bài viết này đưa ra một ví dụ đơn giản về cách sử dụng event mouse hover trong jQuery. Chúng ta thường sử dụng hover của css để thay đổi style của một element. Nếu ta muốn những xử lý phức tạp được thực thi khi hover thì css không thể đáp ứng được => Vậy ta phải tự viết.

Syntax: .hover(MouseInFunction, MouseOutFunction)

  • MouseInFunction: Hàm được gọi tới khi con trỏ di chuyển vào element.
  • MouseOutFunction: Hàm được gọi tới khi con trỏ di chuyển ra khỏi element.

Ví dụ: Khi di chuyển con trỏ chuột vào ảnh thì ảnh sẽ được phóng to ra, khi con trỏ chuột rời khỏi ảnh kích thước ảnh trở lại như cũ.


Code
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("[name='hover_image']").css("top",(jQuery("#hover_div").position().top + 20)+"px");
var left = 40;
jQuery("[name='hover_image']").each(function(i,val){
jQuery(this).css("left",(jQuery("#hover_div").position().left + left)+"px");
left+=100;
});
jQuery("[name='hover_image']").hover(function(){//ham callback hoverIn
jQuery(this).animate({
width:"+=20",
height:"+=20",
left:"-=10",
top:"-=10",
opacity:"1",
filter:"alpha(opacity=100)"
},300);
},function(){//ham callback hoverOut
jQuery(this).animate({
width:"-=20",
height:"-=20",
left:"+=10",
top:"+=10",
opacity:"0.4",
filter:"alpha(opacity=40)"
},300);
});
});
</script>
<style>
#hover_div img{
float:left;
position:absolute;
width:60px;
height:60px;
opacity:0.4;
filter:alpha(opacity=40)
}
</style>
<div id="hover_div" style="height:120px;background-color:#FBF9EA;border:1px solid black;">
<img name="hover_image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhX0KCZGWY-pbPmlFERA5PqYs5mcXV5UGQK3xdvJbr1VgbAffbht0M_Q9rTovIa3XlOcLMIhqRy7SaLDQL6iuyom6qjIQUzh71I5rd9-K1L7eErhpX-nNf1ELE1oqFd1v9OuPwKAB82mIJY/s400/puppy"/>
<img name="hover_image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhX0KCZGWY-pbPmlFERA5PqYs5mcXV5UGQK3xdvJbr1VgbAffbht0M_Q9rTovIa3XlOcLMIhqRy7SaLDQL6iuyom6qjIQUzh71I5rd9-K1L7eErhpX-nNf1ELE1oqFd1v9OuPwKAB82mIJY/s400/puppy"/>
<img name="hover_image" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhX0KCZGWY-pbPmlFERA5PqYs5mcXV5UGQK3xdvJbr1VgbAffbht0M_Q9rTovIa3XlOcLMIhqRy7SaLDQL6iuyom6qjIQUzh71I5rd9-K1L7eErhpX-nNf1ELE1oqFd1v9OuPwKAB82mIJY/s400/puppy"/>
</div>

Demo


4 nhận xét: