嗨,当我将鼠标悬停在下方的其他三个方框时,我无法在顶部中间的框中显示背景图像。现在只显示文本。感谢您的任何帮助,您可以提供。如果您需要更多说明,请告诉我。
我相信这是问题代码:
document.getElementById('message').style.backgroundImage = `"url('${element.src}')";`;
console.log(`"url('${element.src}')";`);
}
这是codepen: https://codepen.io/vaughnick/pen/VygjZw
答案 0 :(得分:1)
您必须更改此"url('${element.src}')"
;
像这样的`url($ {element.src})`;
function showProperties(element){
document.getElementById('message').innerHTML = element.alt;
document.getElementById('message').style.backgroundImage = `url(${element.src});`;
console.log(`url(${element.src})`);
}

body{
margin: 2%;
border: 1px solid black;
background-color: #b3b3b3;
}
#message{
line-height:100px;
text-align:center;
width: 575px;
height: 100px;
border:5px solid black;
margin:0 auto;
margin-bottom:10px;
background-color: #8e68ff;
background-image: url('');
font-size: 150%;
}
.preview{
width:10%;
margin-left:17%;
border: 10px solid black;
}
img{
width:95%;
}

<h1> This and Template Literals</h1>
<div id = "message">
Hover over an image to display the alt text.
</div>
<img class = "preview" alt = "Styling with a Bandana" src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg" onmouseover = "showProperties(this)" onmouseleave = "document.getElementById('message').innerHTML='Hover over an image';">
<img class = "preview" alt = "With My Boy" src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon2.JPG" onmouseover = "showProperties(this)" onmouseleave = "document.getElementById('message').innerHTML='Hover over an image';">
<img class = "preview" src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon3.jpg" alt = "Young Puppy" onmouseover = "showProperties(this)" onmouseleave = "document.getElementById('message').innerHTML='Hover over an image';">
&#13;
答案 1 :(得分:1)
您需要删除url()
周围的引号。
document.getElementById('message').style.backgroundImage = `url('${element.src}')`;
// ^ ^ without
// "