2016-01-04 46 views
0

我每次点击按钮时都会移动div。它应该总是移动相同的距离。我正在用JavaScript做这件事,但我似乎无法在第一次点击后使它工作。与JS一起使用“transform:translate”只能工作一次

HTML

<div id="container"> 
    <div class="slide"></div> 
    <div class="slide"></div> 
    <div class="slide"></div> 
</div> 
<button id="move">Click to move the square</button> 

CSS

.slide { 
    display: inline-block; 
    width: 100px; 
    height: 100px; 
    background: lightblue; 
    margin-bottom: 10px; 
    margin-right: 10px; 
} 

JS

document.getElementById("move").addEventListener("click", function() { 
    document.getElementById("container").style.transform = "translateX(30px)" 
}) 

我已经打过电话从事件侦听器之外的功能,如:

document.getElementById("move").addEventListener("click", clickNext); 
function clickNext() { 
    document.getElementById("container").style.transform = "translateX(30px)" 
} 

我也试图通过HTML与 “点击” 属性来处理单击事件:

HTML

<button id="move" onclick="clickNext()">Click to move the square</button> 

JS

function clickNext() { 
    document.getElementById("container").style.transform = "translateX(-100px)" 
} 

在这些代码的每一个位按钮按预期工作,但只能使用一次。之后,按钮停止工作。

任何有关为什么会发生这种情况的帮助将不胜感激。

回答

1

,因为在该style性质没有改变被分配在点击第二次出现,因此没有animation

试试这个:完美

var amount = 30; 
 
var initial = 0; 
 
document.getElementById("move").addEventListener("click", function() { 
 
    initial += amount; 
 
    document.getElementById("container").style.transform = "translateX(" + initial + "px)" 
 
})
.slide { 
 
    display: inline-block; 
 
    width: 100px; 
 
    height: 100px; 
 
    background: lightblue; 
 
    margin-bottom: 10px; 
 
    margin-right: 10px; 
 
}
<div id="container"> 
 
    <div class="slide"></div> 
 
    <div class="slide"></div> 
 
    <div class="slide"></div> 
 
</div> 
 
<button id="move">Click to move the square</button>

+1

作品,谢谢很多。 – SoKeT