使用Javascript移动/动画Div

时间:2015-06-01 19:01:53

标签: javascript html move

我想使用javascript移动div

例如,如何使用javascript将div移动到左侧50px?

我希望在点击链接后启动该功能。任何人都知道如何做到这一点?

2 个答案:

答案 0 :(得分:0)

这是有用的:

HTML:

<div class="container">
    <span id="box"></span>
</div>
<a href="#" id="move-test">Move test element.</a>

CSS:

.container {
    position: relative;
    width: 100%;
    height: 50px;
    padding: 10px;
    background-color: beige;
    margin-bottom: 20px;
}

#box {
    position: absolute;
    top: 10px;
    left: 100px;
    height: 30px;
    width: 30px;
    background-color: blue;
}

Javascript:请把它放在文档就绪函数中。

$("#move-test").on('click', function (e) {
    e.preventDefault();
    moveBox();
});

var moveBox = function(){
    var $box = $("#box");
    var left = $box.position().left;
    left = left - 20;
    $box.css('left', left + 'px');
};

这是一个不断移动的jsfiddle:

https://jsfiddle.net/5ncb6szg/

答案 1 :(得分:0)

您应该使用position: relative因为负边距不受欢迎。将默认值设置为left: -100%,这意味着元素应该向左移动与宽度相同的量。对于javascript,我们将单击处理程序分配给脚本中的链接而不是内联。分配变量open=false,因为它在第一次加载时关闭,然后在我们打开它时将变量赋值给open=true。这样就可以在不查询dom的情况下为元素提供状态。

&#13;
&#13;
var hidden = true;
var box = document.getElementById("box");
document.getElementById('toggle').onclick = function() {
    if(hidden) hidden = false, box.style.left = 0; 
    else hidden = true, box.style.left = '-100%';
}
&#13;
#box {
    background: red;
    height: 50px;
    width: 50px;
    position: relative;
    left: -100%;
}
&#13;
<a href="javascript:void(0)" id="toggle">
  <h3 id="contact">Contact</h3>
</a>
<div id="box"></div> 
&#13;
&#13;
&#13;

相关问题