繁体   English   中英

根据鼠标的位置在div内滑动元素

[英]Slide element inside a div depending of the mouse entry position

我想在div内插入一个元素,但是滑动位置应该有所不同。

<div class="block">
    <div class="hover">…</div>
</div>

如果用户从左侧输入div,则该元素应从左侧滑动,如果从右侧进入,则该元素应从右侧滑动,其他方向相同。

同样对于顶部/底部,我将需要保存到变量中,即用户输入div的那一侧,并根据变量的值触发函数。

如何确定方向/位置? 我正在使用jQuery libraray,但是纯JavaScript也可以接受。

基本上,您需要做的是使用jQuery的mouseover并从事件对象中获取clientX和clientY。 然后,将该信息与offset(),height()和width()结合使用,以确定它们来自<div>哪一侧。 例:

<!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>

(抱歉,久等了 ;)

这是我更新的示例,未经测试-但是应该可以使用。

$(".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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM