javascript,offsetTop,offsetBottom

时间:2017-02-07 17:22:20

标签: javascript offset

我的html id中有一个段落标记是移动的,我正在尝试移动p标签以减慢页面加载时的下降。但是我的代码没有用.......

var speed = 12;
var direction = 1;
var getParagraph = document.getElementById("move");
getParagraph.onmouseover =  moving;

function moving() {
    var bo = getParagraph.offsetHeight;
    var boTop = getParagraph.offsetTop;
    var boBottom = boTop + bo;

    // When right side of the box goes too far - change direction:
    if (boBottom > document.body.offsetHeight) {
        direction = -1;
    }

    // When left side of the box goes too far - change direction:
    if (boTop < 0) {
        direction = 1;
    }

    // Recalculate position:
    getParagraph.style.Top = (boTop + speed * direction)
}

1 个答案:

答案 0 :(得分:0)

这是您的代码稍作修改,并且“有效”:

JS:

var speed = 12;

    var direction = 1;

    var getParagraph = document.getElementById("move");

    document.getElementById("move").addEventListener("mouseover", moving);
     //getParagraph.onmouseover = moving;

    function moving() {

        console.log("Moving??");
        var bo = document.getElementById("move").offsetHeight;

        var boTop = document.getElementById("move").offsetTop;

        var boBottom = boTop + bo;

        // When right side of the box goes too far - change direction:

        if (boBottom > document.body.offsetHeight) {
            direction = -1;
        }
        // When left side of the box goes too far - change direction:

        if (boTop < 0) {

            direction = 1;
        }
        // Recalculate position:
        document.getElementById("move").style.marginTop = (boTop + speed * direction) + "px";
        speed++;
    }

CSS:

 #move {
           display : block ;
           position : absolute ; 
        }

希望它有所帮助。