![](/img/trans.png)
[英]How to position the center of a div to the center of the mouse cursor on mouse movement with JS?
[英]mouse pointer position center of div on first and last element
我遇到了這個jquery示例,該示例根據鼠標在mouseenter或mousemove上的位置向左或向右移動div。 它使用一個名為$ .throttle的jquery類,它導致每毫秒執行一次代碼。 我想知道是否有人想過如何將鼠標指針放在第一個和最后一個div元素上或每個div元素上,使其恰好位於每個元素的中心,因此您不必在滾動鼠標時將鼠標指針放在邊緣上元素在左側或右側。 基本上,我希望它具有不能超過的極限。 當您將鼠標指針懸停在示例上時,您將看到即時消息在說什么,單擊此處jsFiddle該示例在jquery 1.5中完成
的HTML
<div id="wrapper">
<ul id="scroll-content">
<li class="item"><img src="http://placehold.it/100x150/09f" /></li>
<li class="item"><img src="http://placehold.it/100x150/2f2" /></li>
<li class="item"><img src="http://placehold.it/100x150/234" /></li>
<li class="item"><img src="http://placehold.it/100x150/342" /></li>
<li class="item"><img src="http://placehold.it/100x150/312" /></li>
<li class="item"><img src="http://placehold.it/100x150/131" /></li>
<li class="item"><img src="http://placehold.it/100x150/111" /></li>
<li class="item"><img src="http://placehold.it/100x150/222" /></li>
<li class="item"><img src="http://placehold.it/100x150/333" /></li>
<li class="item"><img src="http://placehold.it/100x150/122" /></li>
</ul>
CSS:
#wrapper {
width: 100%;
height: 170px;
overflow: hidden;
background-color: red;
}
#scroll-content {
width: 1050px;
}
jQuery的:
$(document).ready(function() {
var wrapper = $('#wrapper'),
content = $('#scroll-content');
wrapper.bind('mouseenter mousemove', $.throttle(200, mousemove));
function mousemove(e) {
var wrapper_width = wrapper.outerWidth(),
content_width = content.outerWidth();
//calculate new left margin
var tmp = e.pageX * (content_width - wrapper_width) / wrapper_width;
content.stop().animate({
'margin-left': '-' + tmp + 'px'
}, 'fast', 'easeOutSine');
}
});
我希望了解你:
JS變更:
//exaggerate mouse-x
var exmousex = (e.pageX-100) * 1.3;
//calculate new left margin
var tmp = exmousex * (content_width - wrapper_width) / wrapper_width;
//LIMITS
if (tmp < 0) tmp = 0;
if (tmp > content_width - wrapper_width -5 ) tmp = content_width - wrapper_width -5;
content.stop().animate({'left': -tmp}, 'fast', 'easeOutSine');
CSS更改:
#wrapper {
position: absolute;
top:0;
left:0
}
#scroll-content {
position: relative;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.