开发者

jquery image hotspots

I'm looking for a jquery script that lets me add hotspots to an image. They way I imagine it to work is like this.

I can drag an image to a location on the image. The location = 开发者_运维问答the dragged image X Y coordinates is retrievable.

Thats it, does anyone know of a script that can help me do that?


This should get you started. You can run this demo here.

The HTML is quite simple. We'll have a draggable <img> element and a <div> that indicates its position.

<!-- This is our position indicator: -->
<div id="status">
    <p>Pixels from top: <span id="top_pos"></span></p>
    <p>Pixels from left: <span id="left_pos"></span></p>
</div>

<!-- ..and this is the draggable element: -->
<div id="draggable" class="ui-widget-content">
    <p>x</p>
</div>

Now for the Javascript code. This uses jQuery and jQueryUI.

$(function() {
    $("#draggable").draggable();

    // Set status indicators to display initial position.
    $("#top_pos").text($("#draggable").position().top);
    $("#left_pos").text($("#draggable").position().left);

    // On dragstop events, update position indicator.
    $("#draggable").bind("dragstop", function(event, ui) {
        $("#top_pos").text(ui.position.top);
        $("#left_pos").text(ui.position.left);
    });

});

The dragstop event is triggered whenever the user lets go of the mouse after dragging the draggable element around.

The ui object passed to the callback function contains additional information about the previous position of the draggable element, etc.


Here's an example of the following.

You can do this without any plugins as long as you cover a few specifics. First, let's set our draggable and droppable elements with absolute positioning:

.draggable, .droppable { position:absolute; }
.draggable { z-index:51; }
.droppable { z-index:50; }

Then, let's set up our images and disable the default drag behavior:

<img src="small_ball.png" class="draggable" ondragstart="return false" />
<br><br>
<img src="cartoon-beach.gif" class="droppable" ondragstart="return false" />

Now we just need handlers for mousedown on a draggable element:

var curDrag;

$(document).bind('mousedown', function (e) {
    if ($(e.target).hasClass('draggable')) {
        curDrag = e.target;
    }
});

Which stores the currently dragged object in a global variable, and now we'll add a handler for a mouseup event on the droppable image:

$(document).bind('mouseup', function (e) {
    if (curDrag && $(e.target).hasClass('droppable')) {
        $(curDrag).css({
            'left': e.pageX,
            'top' : e.pageY
        });
        curDrag = null;
    }
});

So that we'll only move the dragged image if we mouseup over the draggable area. This isn't cross-browser compatible, as you'd need to implement clientX and clientY for IE, but I'll let you figure out how to do that.

Try dragging the beach ball around yourself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜