如何使用jQuery animate()方法使div左右移动? [英] How to make div move right and left using jQuery animate() method?

查看:278
本文介绍了如何使用jQuery animate()方法使div左右移动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请查看以下内容:

http://jsfiddle.net/tmPfV/

如果单击右键,则框将向右移动;如果单击左键,则框将向左移动.但是,如果再次单击鼠标右键,则什么都没有...

If you click right the box moves right and if you click left the box moves left. However if you click right again, nothing...

我如何让它向左和向右移动多次,而不是先工作一圈然后又不工作?

How can I get it to move right and left as many times as I like instead of it working for one round and then not working again?

如果您先左移然后右移也会弄乱,怎么解决呢?

Also if you clock left first and then right it also messes up, how to solve that?

jquery:

            $('.right').click(function(e) {
                e.preventDefault();
                $('#foo').animate({
                    'right' : '30px'    
                });                 
            });
            $('.left').click(function(e) {
                e.preventDefault();
                $('#foo').animate({
                    'left' : '30px'
                });                 
            });

html:

        <a href="" class="left">left</a> | <a href="" class="right">right</a>
        <br /><br />
        <div id="foo" style="background:red;width:100px;height:100px;position:absolute"></div>

推荐答案

第二次尝试进行动画处理时,它已经在第一个动画的右侧保留了30px的位置.

The second time it tries to animate, it already has 30px right positioning left over from the first animation.

为什么它会在左动画的开始处跳转;主体具有填充物,因此默认情况下,滑块会以填充物缩进.当我们在动画开始时将left属性设置为0时,它会跳出填充区域外(到左侧0px的绝对位置).应用0px的正文填充进行修复.

As to why it jumps at the start of the left animation; the body has padding, so by default the sliding block is indented with padding. When we set the left property to 0 at the beginning of the animation, it jumps outside the padding (to the absolute position of 0px left). Apply a body padding of 0px to fix it.

http://jsfiddle.net/MbJJ6/

            $('.right').click(function(e) {
                e.preventDefault();
                $('#foo').css({ 'right': '0px', 'left': '' }).animate({
                    'right' : '30px'    
                });                    
            });
            $('.left').click(function(e) {
                e.preventDefault();
                $('#foo').css({ 'right': '', 'left': '0px' }).animate({
                    'left' : '30px'
                });                    
            });

这篇关于如何使用jQuery animate()方法使div左右移动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆