Javascript 如果单击,我想移动该框

Javascript 如果单击,我想移动该框,javascript,css,Javascript,Css,这是一个简单的问题。如果我点击这个框, 我想把200px移到左边。但这对我来说很难请帮帮我! 问题出在哪里 <style> .box { width: 200px; height: 200px; background-color: red; } .playing { transform: translate(200px); } </style> <title>Document</title> <

这是一个简单的问题。如果我点击这个框, 我想把200px移到左边。但这对我来说很难请帮帮我! 问题出在哪里

<style>
  .box {
    width: 200px;
    height: 200px;
    background-color: red;
  }
  .playing {
    transform: translate(200px);
  }
</style>
<title>Document</title>
</head>
<body>
<div class="box"></div>
<script>
const move = document.getElementsByClassName("box");
move.addEventListener("click", _move);

  function _move(e) {
    move.classList.add("playing");
  }

.盒子{
宽度:200px;
高度:200px;
背景色:红色;
}
.玩{
转换:转换(200px);
}
文件
const move=document.getElementsByClassName(“框”);
move.addEventListener(“单击“,\u移动”);
功能(e){
move.classList.add(“播放”);
}

返回一个而不是单个元素,因此必须将事件侦听器附加到集合中的每个元素

const move=document.getElementsByClassName(“框”);
[…移动].forEach(m=>m.addEventListener(“单击”,移动));
函数_move(){
这个.classList.add(“播放”);
}
.box{
宽度:200px;
高度:200px;
背景色:红色;
}
.玩{
转换:转换(200px);
}

GetElementsByCassName返回数组,因此需要给出索引

var move=document.getElementsByClassName(“框”);
移动[0]。添加EventListener(“单击”,移动);
功能(e){
移动[0]。类列表。添加(“播放”);
}
.box{
宽度:200px;
高度:200px;
背景色:红色;
}
.玩{
转换:转换(200px);
}

用于将其向左移动的css属性不正确。 应该是

.playing {
transform: translateX(200px);
}

你也可以用这个。不要使用document.getElementsByClassName,而是使用document.querySelector

const move=document.querySelector(“.box”);
move.addEventListener(“单击“,\u移动”);
功能(e){
move.classList.add(“播放”);
}
.box{
宽度:200px;
高度:200px;
背景色:红色;
}
.玩{
转换:转换(200px);
}

因为这个问题已经解决了,但我只是在尝试,如果有人想通过单击框来连续移动框,那么这个代码将非常有用


.盒子{
位置:相对位置;
宽度:200px;
高度:200px;
背景色:红色;
}
文件
设偏移量=0;
const move=document.getElementsByClassName(“框”)[0];
move.addEventListener(“单击“,\u移动”);
功能(e){
偏移量+=200;
move.style.left=偏移量+px;
}
$(文档).ready(函数(){
$(“#按钮一”)。单击(函数(){
$('框一').css(“转换”,“翻译(200px,0)”);
});
});
$(文档).ready(函数(){
$(“#按钮二”)。单击(函数(){
$('框二').css(“转换”,“翻译(250px,0)”);
});
});
$(文档).ready(函数(){
$(“#按钮三”)。单击(函数(){
$('boxone,'boxtwo').css(“transform”,“translate(0px,0)”);
});
});
#第一框,
#方框二
{
宽度:100px;
高度:100px;
背景颜色:蓝色;
}
#方框二
{
过渡:0.6s轻松过渡;
}
#按钮三
{
位置:相对位置;
左:100px;
}
身体
{
背景色:#E1E7E8;
}
使用jQuery进行点击翻译 翻译
使用jQuery在单击时平滑翻译 翻译

重置
@webbanditen错误添加:如果您仅提及一个值,则它将被视为translateX。例如,
translate(2)
相当于
translate(2,0)