简体   繁体   中英

moving a cursor image inside a div

I started to develop a sniper game but i am finding a trouble moving the sniper image inside the div my main goal is when the mouse is over the div i want to change it's image to the sniper image that's what i did :

<center>
    <div id="field" class="cursor1">
        &nbsp;
    </div>
</center>

<script type="text/javascript">
    $(document).ready(function() {
        $("#field").mouseover(function() {
            $(this).addClass("cursor");

        });
    });
</script>
<style type="text/css">
    #field
    {
        width:300px;
        height:300px;
        border:1px solid;
    }
    .cursor
    {
        cursor:url("sniper.jpg") ;
    }
</style>

but that didn't work. How can I move the image inside the div?

在此处输入图片说明

I would not suggest setting your mouse image with css, because it's easier to adjust image size and center it with replacing mouse cursor with a real image.

$('#box').mouseenter(function(){ 
    $('img').css('display','block');
});

$('#box').mouseleave(function(){ 
    $('img').css('display','none');
});

$("#box").mousemove(function(event) {
    $('img').css('left',event.pageX-20);
    $('img').css('top',event.pageY-20);
});

I made a simple example of this http://jsfiddle.net/N9pu4/

Also consider using canvas element for rendering graphics.

The basic (CSS 2.1) syntax for this property is:

cursor:  [<url>,]* keyword

This means that zero or more URLs may be specified (comma-separated), which must be followed by one of the keywords defined in the CSS specification, such as auto or pointer.

(see https://developer.mozilla.org/en-US/docs/Web/CSS/cursor/url?redirectlocale=en-US&redirectslug=CSS%2Fcursor%2Furl )

So you should provide a fallback value:

.cursor
{
    cursor:url("sniper.jpg"), auto;
}
#field:hover
{ 
cursor:url("sniper.jpg") ;
}

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