开发者

MouseOver or hover() or css() for changing positions

开发者 https://www.devze.com 2023-04-12 14:08 出处:网络
I have an image on my page and want that it change the position on mouseover or on click, so I tried several things but I cant find the right start.

I have an image on my page and want that it change the position on mouseover or on click, so I tried several things but I cant find the right start.

So I started to change the top-position but that's not working, I would like that on m开发者_StackOverflow社区ouseover the image it jumps to position x/y (maybe random x/y) if I mouseover it again it will jump to another position.

  $('#image').one('click', function () {
     $(this).css( 'top' : '+=200' );
  });

But that's not working so please someone could give me some input that I can figure out what to do?


Note that while setting values for top, jQuery will not automatically get the value of top set previously and add 200 to it(like a normal programming language). You could have seen this as an error in executing if you try to see in a console. You can get the value of top first and then add 200px to it and then set it again.

This should work:

$('#image').one('click', function () {
  var top = parseInt($(this).css("top"));
  $(this).css( 'top' , top+ 200);
});

I had to parse the string to an integer returned by css, you could also substitute that extra operation by some method that returns only the value and not the value with "px" added to it, dunno if there is one already.


Try something like this:

<html>
    <head>
        <script type="text/javascript">
            function switchPos(obj) 
            {
                var divobj = document.getElementById('div1')
                var x = divobj.offsetHeight - obj.height - 5;
                var y = divobj.offsetWidth - obj.width - 5;

                var randomx = Math.floor(Math.random()*x+1);
                var randomy = Math.floor(Math.random()*y+1);

                obj.style.top = randomx + 'px';
                obj.style.left = randomy + 'px';
            }
        </script>
    </head>
    <body>
        <div id="div1" style="width: 800px; background: red;">
            <img src="image.jpg" style="position:relative;" onmouseover="switchPos(this);" onmouseout="switchPos(this);"/>
        </div>
    </body>
</html>
0

精彩评论

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

关注公众号