Javascript Scrolling Image edge detection
Currently I am experimenting with a little Image Zoom/Scroller script that I am trying to create, and yes I know there are plugins out there that do this but I am developing this for a lightweight version and for learning to. The main problem I have now is, that I am not sure how to constrain my image scrolling to only the width and height of 开发者_运维技巧my image. I would like to set up my script to stop the image from scrolling when the user gets to a ceartin width or height of the image to stop the image from being scrolled out of the div. Below is a fiddle to my script, any suggestions or tips to help me move in the right direction would be much appreciated click here to go to fiddle
I built one of these a while ago.
The principle is you listen to three events: mousedown
, mouseup
and mousemove
.
Firstly, it's best to use a div
and then set the image as the background-image
of the div
. This allows you to use background-position
to move the image around inside the div
. We'll call this div
#container
.
On mousedown
, you record the coordinates of the background position of the image. On page load, these will be 0 0
(unless you've told it to be something else; we'll assume you haven't). When the mousedown
event is fired, this is essentially the start of the drag operation, so you'll probably want to set some sort of draggingStarted
variable.
On mousemove
, you want to check if draggingStarted
is true. If it is, work out the relative distance the mouse cursor has moved and change the background image coordinates accordingly.
On mouseup
you want to set your draggingStarted
variable to false. This is so that if the mousemove
event is fired, the image position stays fixed.
Now, the problem you're asking about is that the solution given so far allows the background position coordinates to overshoot the image, so we'll get a partially blank #container
. The solution to this problem is to record the dimensions of the image, and then when you're working out how far to move the background image (in the mousemove
function), check to see whether the new background image coordinates are outside the bounds of the image. If they are, don't allow it!
精彩评论