【问题标题】:More Basic Javascript Animation Problems更多基本的 Javascript 动画问题
【发布时间】:2015-02-06 12:04:26
【问题描述】:

所以现在我尝试实现横向移动:

<!DOCTYPE html>
<html>
<head>
<title>Animation Bullshit</title>
<link rel="stylesheet" href="animation.css"/>
</head>
<body>
<div id="div">
</div>

<script type="text/javascript">
div = document.getElementById("div")

div.onmouseover = move, left; 
div.onmouseout = up;

var cHeight = div.style.height | 150;
var cLeft = div.style.marginLeft | 0;

function move() {
    if (cHeight < 300) {
        cHeight += 10;
        div.style.height = cHeight + "px";
        setTimeout (move, 20);
    }
}

function slide() {
    if (cLeft < 400) {
        cLeft += 10;
        div.style.marginLeft = cLeft + "px";
        setTimeout (slide, 20);
    }
}

function up() {
    if (cHeight > 150) {
        cHeight -= 10;
        div.style.height = cHeight + "px";
        setTimeout (up, 20);
    }
}
</script>
</body>
</html>

一切都加载了,但是当我将鼠标悬停在 div 上时,什么也没有发生。它甚至没有向下扩展。有什么建议吗?

它告诉我要添加更多细节......呃...... div是黑色的,初始margin-left为0px。

【问题讨论】:

  • 您检查过您的控制台吗?你应该得到一个无效的左侧分配。 div.style.margin-left 不起作用。试试div.style["margin-left"]
  • 详细说明@brbcoding的观点,.margin-left是不正确的,你需要使用DOM名称.marginLeft,或者他提到的括号中的字符串。 DOM 名称的效率稍微高一点,但两者都可以。此外,您调用函数onmouseoveronmouseout 的方式很有趣。
  • 好的,我更改了它并使用更改更新了原始帖子。还是行不通。我仍然收到未捕获的引用错误:未定义左侧。

标签: javascript html animation margin


【解决方案1】:

我刚刚使用了您的代码。 这是你想要的?

http://jsfiddle.net/tz2vcote/ 我认为这是因为您没有使用var 声明变量 div。你应该检查一下 firebug 控制台。

签出更新的 http://jsfiddle.net/tz2vcote/2/ 点击 div 获得幻灯片效果。

【讨论】:

  • 更新一个有效。你到底改了什么?我的意思是,显然你的使用单击而不是鼠标悬停,但是移动 div 的基本过程看起来相同......我将如何使用鼠标悬停而不是单击?
  • 不是div变量需要用var声明。我用我的旧代码试过了,但还是不行。
  • 实际上你分配事件处理函数的方式是错误的。 div.onmouseover = 向左移动;相反,您将这两个功能包装到 1 个单个功能中并分配它。像 div.onmouseover = doBoth;其中 doBoth 是一个同时执行这两个功能的函数。
猜你喜欢
  • 2015-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-01
  • 2011-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多