为什么对象不能点击按钮? [英] Why is the object not moving on clicking the button?
问题描述
该对象不会点击按钮。为什么会这样?
function animate(){var object = document。 。的getElementById( '对象')的样式; var x = 100; object.left = x +'px';}
# object {position:absolute;顶部:50px; right:20px; left:20px; height:40px;宽度:80px; background-color:green;}
如果我们假设对象
id的元素是按钮,那么您只需将一个事件侦听器附加到它上面,以使<$ c
const object = document.getElementById($ c $ animate
'目的');
object.addEventListener('click',animate,false);
现在我们只需要重写动画
函数,以便移动与点击相关的元素。
函数animate(){
var x = 100;
this.style.left = x +'px';
}
如果你不想让你的按钮成为那个对象,一个HTML按钮:
< button id =button>点击我< / button>
然后将事件侦听器添加到按钮:
const button = document.getElementById('button');
button.addEventListener('click',animate,false);
然后将您的 animate
函数恢复为它的方式。在这里,我仅捕获对象
变量中的元素,因为它对您使用的变量名称更有意义。
函数animate(){
const object = document.getElementById('object');
var x = 100;
object.style.left = x +'px';
}
$ b 注意:如果您正在使用的浏览器支持模板文字你的
animate
函数的最后一行可以是: object.style .left =`$ {x} px`;
The object is not moving on clicking the button. Why is it so?
function animate() {
var object = document.getElementById('object').style;
var x = 100;
object.left = x + 'px';
}
#object {
position: absolute;
top: 50px;
right: 20px;
left: 20px;
height: 40px;
width: 80px;
background-color: green;
}
If we assume that your element with the object
id is the button, then all you need to do is attach an event listener to it so that the animate
function is called when you click it.
const object = document.getElementById('object');
object.addEventListener('click', animate, false);
Now we just need to rewrite your animate
function so that it moves the element associated with the click.
function animate() {
var x = 100;
this.style.left = x + 'px';
}
If you don't want your button to be that object, add a button to the HTML:
<button id="button">Click me</button>
then add the event listener to the button:
const button = document.getElementById('button');
button.addEventListener('click', animate, false);
And then revert your animate
function back to the way it was. Here I've captured the element only in the object
variable, as it makes more sense with the variable name you're using.
function animate() {
const object = document.getElementById('object');
var x = 100;
object.style.left = x + 'px';
}
Note: if the browsers with which you're working support template literals the last line of your animate
function can be:
object.style.left = `${x}px`;
这篇关于为什么对象不能点击按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!