鼠标移动时在div内移动div

时间:2017-03-24 09:21:24

标签: javascript jquery onmousemove

有人可以帮我解决一个问题。所以我有两个div div1需要是浏览器屏幕的高度和宽度以及隐藏的流量。

在那个div中我有另一个div div2,它是第一个div的宽度和高度的两倍。然后我需要在鼠标移动时移动该div。

#view-window {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
}

#background-wrapper {
  background: url('../images/background.png') no-repeat center center;
  background-size: 100% 100%;
  position: absolute;
}
<div id="view-window">
  <div id="background-wrapper">
  </div>
</div>

有点像这样但是当我的鼠标位于视图框的左上角时,红色框的顶部顶部也应该在那个角落。

https://codepen.io/anon/pen/bqKogL

2 个答案:

答案 0 :(得分:2)

试试这段代码:

&#13;
&#13;
<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8"/>
		<title></title>
	</head>
	<body>	
		<style type="text/css">
			#move {
				height: 100px;
				width: 100px;
				position: absolute;
				top: 0;
				left: 0;
				background: green;
			}
		</style>
		<div id="move">
		</div>
		<script type="text/javascript">
			var div = document.getElementById('move');
			document.addEventListener('mousemove',function(e) {			
				div.style.left = e.pageX+"px";
				div.style.top = e.pageY+"px";
			});
		</script>
	</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用以下代码:

$(document).ready(function(){
    var $moveable = $('.moveAble');
    $(document).mousemove(function(e){
        $moveable.css({'top': e.pageY,'left': e.pageX});
    });
    
    $(".outer").height($(window).height());
    $(".outer").width($(window).width());
});
.moveAble {
    position: absolute;
}

.info {
  background-color:red;
  height: 50px;
  width:50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer">
  <div class="moveAble">
    <div class="info"></div>
  </div>
</div>  

相关问题