简体   繁体   English

使用javascript根据div的高度调整顶部位置

[英]Adjust top position according to height of div with javascript

function jsiBoxAdjustTop()
{
    var top
    if ( jsiBox.preloadImg.height <= 699){
        top = 216;

    }
    else{
        top = 17;
    }
    jsiBox.boxNode.style.top = (top) + 'px';

}

I'm using that function to adjust a div's top position depending on the image that is in it's height. 我正在使用该功能来调整div的顶部位置,具体取决于其高度中的图像。 It's on a light box sort of script so every time I click the next button, a new image which could either be taller or smaller appears. 它在灯箱脚本上,因此每次我单击下一个按钮时,都会出现一个新的图像,该图像可以更高或更低。 It's working alright and it adjusts its position when the image is taller but my problem is it just jumps to that position. 它工作正常,当图像更高时会调整其位置,但是我的问题是它只是跳到了那个位置。 I'm really new to javascript so can anyone help me out to make this as if it's travelling/animating to it's position? 我对javascript真的很陌生,所以有人可以帮助我做到这一点,就好像它在旅行/动画到其位置一样吗? I tried using setTimeOut but I think I was doing it wrong. 我尝试使用setTimeOut,但我认为做错了。 I'd really love to know what I'm doing wrong. 我真的很想知道我在做什么错。

Here's the full script if that helps. 如果有帮助,这里是完整的脚本。 Link 链接

you can use jQuery or YUI to do animate, such as 您可以使用jQuery或YUI进行动画处理,例如

jQuery(jsiBox.boxNode).animate({'top': top}, 3000);

or you can write some simple code with setTimeout just for this case; 或者您可以为这种情况使用setTimeout编写一些简单的代码;

following code assume the begin top is 0. 以下代码假定开始的顶部为0。

var boxStyle = jsiBox.boxNode.style;

function animateTop(to) {
    boxStyle.top = parseInt(boxStyle.top, 10) + 1 + 'px';
    if (parseInt(boxStyle.top, 10) != to) {
        setTimeout(function() {
            animate(to);
        }, 50);
    }
}

animateTop(top);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM