首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >javascript、offsetTop、offsetBottom

javascript、offsetTop、offsetBottom
EN

Stack Overflow用户
提问于 2017-02-08 01:22:20
回答 1查看 6.6K关注 0票数 2

我的html id中有一个段落标签是move,我正在尝试将p标签移动到在页面加载时减速下降。但是我的代码不能工作......

代码语言:javascript
运行
复制
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)
}
EN

回答 1

Stack Overflow用户

发布于 2017-02-08 02:58:19

这是你的代码,只做了很小的改动,它是“工作的”:

JS:

变速= 12;

代码语言:javascript
运行
复制
    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:

代码语言:javascript
运行
复制
 #move {
           display : block ;
           position : absolute ; 
        }

希望能有所帮助。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42096108

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档