Slide element inside a div depending of the mouse entry position
I would like to slide-in an element inside a div, but the sliding position should vary.
<div class="block">
<div class="hover">…</div>
</div>
If the user enters the div from left the element should slide from left, if from right the element should slide in from right, same for the other sides.
Also for top/bottom, I will require to save to a variable, the side from which the user entered the d开发者_如何学Goiv and trigger a function depending on the value of the variable.
How can I determine the direction/position? I'm using the jQuery libraray, but plain JavaScript is also acceptable.
Basically, what you would have to do is use jQuery's mouseover
and get the clientX and clientY from the event object. Then use that info in conjunction with offset(), height(), and width() to determine which side of the <div>
they're coming from. Example:
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title></title>
</head>
<body>
<div id="box" style="width:200px;height:200px;background:red;position:absolute;top:100px;left:100px;"><div id="cover" style="position:absolute;background:blue;width:0;height:0;overflow:hidden;z-index:50;"></div></div>
<script>
$(function(){
var $box = $('#box').mouseenter(function(event){
// coming from the top
if (Math.abs(event.pageY - offset.top) < 10) {
$cover.css('width',width).animate({
height:height
})
}
//coming from the left
else if (Math.abs(event.pageX - offset.left) < 10) {
$cover.css('height',height).animate({
width:width
})
}
//coming from the bottom
else if (Math.abs(event.pageY - (offset.top + height)) < 10) {
$cover.css({
width:width,
top:'auto',
bottom:0
}).animate({
height:height
})
}
//coming from the right
else {
$cover.css({
height:height,
left:'auto',
right:0
}).animate({
width:width
})
}
}).mouseleave(function(){
// reset it
$cover.css({
width:0,
height:0,
bottom:'auto',
right:'auto',
left:'auto',
top:'auto'
})
}), $cover = $('#cover'), offset = $box.offset(), width = $box.width(), height = $box.height()
})
</script>
</body>
</html>
(Sorry for the wait ;)
Here is my updated sample, it is untested - however it should work.
$(".block").mouseenter(function(event){
if(!$(".hover").is(":animated")){
if(event.pageX > ($(".block").position().left + ($(".block").width()/2)))
{
$(".hover").css("left", "-100px");
} else {
$(".hover").css("left", "200px");
{
$(".hover").animate({ left : 0 },300);
}
});
css
.block {
position: relative;
height: 100px;
width: 100px;
overflow: hidden;
background-color: #fff;
}
.block .hover {
position: absolute;
left: -100px;
height: 100px;
width: 100px;
background-color: #00f;
}
精彩评论