2017-06-16 62 views
1

因此,代码的第一部分创建一个按钮,单击时显示图像。但是,代码的第二部分应该是在悬停时使图像更大,但它似乎不起作用。我通过控制台运行这个鳕鱼,它没有给我任何东西。有任何想法吗?为什么第二个事件监听器不工作?

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"; 
}) 
+0

正确的事件名称为['onmouseover' ](https://www.w3schools.com/jsref/event_onmouseover.asp)。 –

回答

0

的想法是正确的,但使用的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"); 
    }); 
}; 

您可以自己尝试一下在这个plunker