简体   繁体   English

为什么第二个事件监听器不起作用?

[英]Why is the second Event Listener not working?

So the first part of the code creates a button that when clicked, displays an image. 因此,代码的第一部分创建了一个按钮,单击该按钮可显示图像。 However, the second part of the code is supposed to make the image larger upon hovering but it doesnt seem to work. 但是,代码的第二部分应该在悬停时使图像变大,但它似乎不起作用。 I ran this cod through the console and it gave me nothing. 我通过控制台运行这个鳕鱼,它什么也没给我。 Any ideas? 有任何想法吗?

  var button = document.getElementById("image");
var image = document.createElement("img");

button.addEventListener("click", function() {

    image.setAttribute("src", "https://www.w3schools.com/css/trolltunga.jpg");
    image.setAttribute("height", "400");
    image.setAttribute("width", "500");
    document.body.appendChild(image);
});

image.addEventListener("mouseover", function(){
    image.style.width = "700";
    image.style.height = "700";
})

The idea is correct, but use setAttribute for your image size as well: 这个想法是正确的,但也可以使用setAttribute作为图像大小:

// Code goes here
window.onload = function() {
var button = document.getElementById("image");
var image = document.createElement("img");

  button.addEventListener("click", function() {
      image.setAttribute("src", "https://www.w3schools.com/css/trolltunga.jpg");
      image.setAttribute("height", "400");
      image.setAttribute("width", "500");
      document.body.appendChild(image);
  });

  image.addEventListener("mouseover", function(){
      image.setAttribute("width", "700");
      image.setAttribute("height", "700");
  });
};

You can try it out yourself in this plunker 你可以在这个plunker自己尝试一下

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM