簡體   English   中英

如何使div跟隨鼠標?

[英]How to get a div to follow mouse?

因此,這是我要實現的目標的鏈接: 模板當將鼠標懸停在計划上時,框會跟隨鼠標。 我正在嘗試重新創建同樣的東西。

到目前為止,這是我的演示,這是一個小演示,我知道它與實際網站上的外觀還差得遠:

HTML:

<div class="centerdiv">
<div class="container">
<div id="follow"></div>
</div></div>

CSS:

#follow{
position : relative;
background-color : grey;
width:75px;
height:150px;
}

.centerdiv {
width:150px;
margin-left:auto;
margin-right:auto;
position:relative;
}
.container
{
width:150px;
height:150px;   
position:absolute;
top:0;
left:0;
overflow:hidden;
border:1px solid #000000;
}

JS:

var mouseX = 0, mouseY = 0, limitX = 150-15, limitY = 150-15;
$('.container').mousemove(function(e){
$("#follow").show();
var offset = $('.container').offset();
console.log(e);
mouseX = Math.min(e.pageX - offset.left, limitX);
mouseY = Math.min(e.pageY - offset.top, limitY);
if (mouseX < 0) mouseX = 0;
if (mouseY < 0) mouseY = 0;
});

$('.container').mouseleave(function() {
$("#follow").hide(); 
});    


var follow = $("#follow");
var xp = 0, yp = 0;
var loop = setInterval(function(){
xp += (mouseX - xp) / 5;
yp += (mouseY - yp) / 5;
follow.css({left:xp, top:yp});

}, 30);

jsfiddle演示

請有人指導我正確的方向

先感謝您!

首先,您應該將DIV height:100%;設置height:100%; 就像Semplice。
之后,在元素中心設置鼠標位置,您應該計算DIV寬度並將其設置為左邊距的一半

var halfwidth = ($("#follow"))/2;
$("#follow").css('margin-left',halfwidth);

我希望我說對了:)

圖片跟隨鼠標<div></div><div id="text_translate"><p>如何在特定的&lt;div&gt;中使圖片跟隨鼠標?</p><p> 我知道我可以從e.pageX &amp; e.pageY和代碼document.onmousemove = followmouse;獲得鼠標 position . Run the followmouse function every moment the mouse move in a page and in the followmouse function, set the picture position to the mouse position. 對於我在這里提出的確切問題(如何在特定的&lt;div&gt;中使圖片跟隨鼠標),我有這個想法:</p><p> 獲取我的 div <em>top</em> 、 <em>left</em> 、 <em>width</em>和<em>height</em>並做一些數學運算,如果鼠標 go 離開div ,設置圖片的visibility:hidden 。</p><p> 但是沒有任何簡單的方法可以做到這一點嗎?</p></div>

[英]Picture follow a mouse in a <div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM