点击鼠标时,如何在CSS
的帮助下使广场流畅运动。只需要移动流畅性,然后方块超出矩形,任务就不重要了。
let cube = document.querySelector('[id="cube"]');
let field = document.querySelector('[id="field"]');
field.onclick = function(event) {
cube.style.left = event.clientX + 'px';
cube.style.top = event.clientY + 'px';
}

#field {
width: 200px;
height: 150px;
border: 10px groove black;
overflow: hidden;
cursor: pointer;
}
#cube {
position: absolute;
left: 0;
top: 0;
width: 40px;
height: 40px;
}

<div id="field">
<img src="https://image.prntscr.com/image/ZfIPM5SZT9qpWY2xZAx3FQ.png" id="cube">
</div>
&#13;
答案 0 :(得分:2)
您可以使用转换 - 当我添加transition: all 1s linear;
之类的内容时,请参阅下面的演示,或者它可以更像特定:
transition: top 1s linear, left 1s linear
您可以查看计时功能并在适当时使用。
使用 ease
查看下面的演示
let cube = document.querySelector('[id="cube"]');
let field = document.querySelector('[id="field"]');
field.onclick = function(event) {
cube.style.left = event.clientX + 'px';
cube.style.top = event.clientY + 'px';
}
#field {
width: 200px;
height: 150px;
border: 10px groove black;
overflow: hidden;
cursor: pointer;
}
#cube {
position: absolute;
left: 0;
top: 0;
width: 40px;
height: 40px;
transition: top 1s ease, left 1s ease;
}
<div id="field">
<img src="https://image.prntscr.com/image/ZfIPM5SZT9qpWY2xZAx3FQ.png" id="cube">
</div>
答案 1 :(得分:1)
尝试将以下代码插入到#cube
-webkit-transition: all 1s;
-moz-transition: all 1s;
-o-transition: all 1s;
-ms-transition: all 1s;
transition: all 1s;
答案 2 :(得分:1)
是的,可以通过将transition:all .2s ease;
添加到多维数据集的CSS中来实现。
let cube=document.querySelector('[id="cube"]');
let field=document.querySelector('[id="field"]');
field.onclick=function(event) {
cube.style.left=event.clientX + 'px';
cube.style.top=event.clientY + 'px';
}
#field {
width: 200px;
height: 150px;
border: 10px groove black;
overflow: hidden;
cursor: pointer;
}
#cube {
position: absolute;
left: 0;
top: 0;
width: 40px;
height: 40px;
-webkit-transition: all .2s ease;
-moz-transition: all .2s ease;
-o-transition: all .2s ease;
-ms-transition: all .2s ease;
transition:all .2s ease;
}
<div id="field">
<img src="https://image.prntscr.com/image/ZfIPM5SZT9qpWY2xZAx3FQ.png" id="cube">
</div>
答案 3 :(得分:0)
我会这样做:
let cube = document.querySelector('[id="cube"]');
let field = document.querySelector('[id="field"]');
field.onclick = function(event) {
cube.style.transform = "translate(" + event.clientX + "px, " + event.clientY + "px)";
cube.style['-webkit-transform'] = "translate(" + event.clientX + "px, " + event.clientY + "px)";
}
#field {
width: 200px;
height: 150px;
border: 10px groove black;
overflow: hidden;
cursor: pointer;
}
#cube {
position: absolute;
left: 0;
top: 0;
width: 40px;
height: 40px;
transition-duration: 1s;
transition-property: top left;
-webkit-transition-duration: 1s;
-webkit-transition-property: top left;
}
<div id="field">
<img src="https://image.prntscr.com/image/ZfIPM5SZT9qpWY2xZAx3FQ.png" id="cube">
</div>
修改强>
我不会使用all,因为其他元素可能需要不同的参数。
我的示例错过了其他浏览器支持,因此也为它们添加代码:
-moz-transition
-o-transition
-ms-transition