Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用JavaScript移动HTML div?_Javascript_Html - Fatal编程技术网

如何使用JavaScript移动HTML div?

如何使用JavaScript移动HTML div?,javascript,html,Javascript,Html,我想我的div包含文本移动10px的权利,每次点击 以下是HTML: <div id='color-div' style='clear:both; position:relative; left:0;'>&nbsp;</div> 我的事件已经定义好了,其他一切都正常工作 要将div向右移动,应将其添加到左侧,而不是右侧 您需要将clickhandler添加到div中。 您正在将样式设置为固定值,以增加它。 加 ,并将javascript更改为: var move

我想我的div包含文本移动10px的权利,每次点击

以下是HTML:

<div id='color-div' style='clear:both; position:relative; left:0;'>&nbsp;</div>
我的事件已经定义好了,其他一切都正常工作

要将div向右移动,应将其添加到左侧,而不是右侧 您需要将clickhandler添加到div中。 您正在将样式设置为固定值,以增加它。 加

,并将javascript更改为:

var moveRight = function(){
    var current_offset = parseInt(document.getElementById('color-div').style.left);
    document.getElementById('color-div').style.left = current_offset + 10 + "px";
}

在这里查看:

您可能想使用这个小javascript

<script language="javascript">
function example_animate(px) {
    $('#example').animate({
        'marginLeft' : px
    });
}
</script>
<input type="button" value="Move Right" onclick="example_animate('+=50px')" />

不要在按钮单击时移动它,而是在div click事件中调用此函数。

使用jquery,您可以通过以下方式实现此目的:

HTML:

<div class="click-me"></div>
Javascript:

$(document).ready(function() {
    $('.click-me').click(function() {
        $this = $(this);
        var currentLeft = $this.offset().left;
        $this.css("left", currentLeft + 10);      
    });
});

您最好切换一个类,该类的定义将div移动到正确的位置;只需将right的值设置为10px。您希望将其当前值增加10。您不是将其移动10px,而是将其设置为10px。您必须获得当前位置并向其添加10。javascript标记为not jquery javascript标记为not jquery
<div class="click-me"></div>
.click-me {
    display:block;
    height:50px;
    width:50px;
    background:blue;    
    position:absolute;
}
$(document).ready(function() {
    $('.click-me').click(function() {
        $this = $(this);
        var currentLeft = $this.offset().left;
        $this.css("left", currentLeft + 10);      
    });
});