简体   繁体   中英

mouse pointer position center of div on first and last element

I came across this jquery example of animating a div to the left or right depending on position of the mouse on mouseenter or mousemove. It uses a jquery class called $.throttle which causes an execution of the code every milliseconds. I was wondering if someone new how to have the mouse pointer over the first and last div elements or over every div element to exactly in the center of each element so you don't have to have the mouse pointer right on the edge whe scrolling the element to the left or right. Basically I want it to have a limit that it can't go past aswell. You will see what im saying when you put you're mouse pointer over the example click here jsFiddle the example is done in 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');
}
});

i hope understand you:

JS changes:

//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 changes:

#wrapper {
    position: absolute;
    top:0;
    left:0
}
#scroll-content {
    position: relative;
}

Try: http://jsfiddle.net/karacas/RkbP6/181/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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