使用jQuery移动div

时间:2013-10-20 00:22:48

标签: jquery css

我想知道如何移动div(box2)一直到屏幕右侧,当用户将鼠标悬停在另一个div(box1)上时消失。我知道我们必须使用Jquery。到目前为止我知道如何通过使用切换功能使box2消失,但我不确定如何使用animate函数将其移动到右边然后消失。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:2)

在屏幕上滑动元素然后将其淡出的一种方法:

    // get the widths of the window (or the parent of the element to move):
var winWidth = $(window).width(),

    // get the width of the element itself:
    demoWidth = $('#demo').width(),

    // find out how far to move the element:
    delta = winWidth - demoWidth,

    // the time-frame over which to animate:
    duration = 1500;

// bind the animate method:    
$('#demo').animate({
    // move the element the distance held by the 'delta' variable:
    'left': delta
// animate for the duration defined by 'duration':
}, duration,

// callback function, to occur once first stage of the animation has completed:    
function () {
    // binding the fadeOut() method:
    $(this).fadeOut(duration);
});

JS Fiddle demo

上面的演示使用(简单)HTML:

<div id="demo"></div>

CSS:

#demo {
    width: 5em;
    height: 5em;
    background-color: #f00;
    /* to move an element, using the 'left' property,
       the 'position' must be set to a value other than 'static' (the default):
    */
    position: relative;
}

要做同样的事情,一旦#box1元素悬停在上面:

var winWidth = $(window).width(),
    demoWidth = $('#box2').width(),
    delta = winWidth - demoWidth,
    duration = 1500;

$('#box1').mouseenter(function () {
    $('#box2').animate({
        'left': delta
    }, duration,

    function () {
        $(this).fadeOut(duration);
    });
});

JS Fiddle demo

以上使用以下HTML:

<div id="box1"></div>
<div id="box2"></div>

参考文献:

答案 1 :(得分:0)

你问的是如何使用$ .animate()?

http://api.jquery.com/animate/

基本上...

$(document).ready()
{
    $(selector).animate(
        {
            "backgroundColor" : "red"
        }, 500, "swing");
}

插入你的选择器,你应该知道如何做到这一点。

Animate有两个主要论点,但我添加了第三个,即“缓和”。

第一个是包含CSS更改的对象文字。

第二个是动画完成的时间(以毫秒为单位)。

第三个是缓动,它允许您在曲线上设置动画。默认为“线性”,看起来很僵硬。

你的问题似乎并不存在。如果您只是要求提供一般信息,请先尝试在搜索引擎中查找。

答案 2 :(得分:0)

有很多方法可以做到这一点,但你可以考虑在悬停时使用hover()和animate()。

<div class='slide-right'>howdy</div>
<div class='slide-right'>doody</div>

完全取决于您使用哪些属性进行右侧滑动。这里我以左边距为动画作为示例。这将具有布局含义,因此请考虑使用left和绝对定位。您可以选择在不透明度滑入和滑出视图时为其设置动画。

$('.slide-right').hover(function() 
                        { 
                          $(this).siblings('.slide-right').animate({ 'margin-left': '+=50' }); 
                        },    
                        function() 
                        { 
                          $(this).siblings('.slide-right').animate({ 'margin-left': '-=50' }); 
                        });
相关问题