JS This 和模板字面量实践

JS This and Template Literals Practice

您好,将鼠标悬停在下面的其他三个框时,我无法让背景图像出现在顶部中间的框内。现在只有文本出现。感谢您的任何帮助,您可以提供。如果您需要更多说明,请告诉我。

我认为这是问题代码:

 document.getElementById('message').style.backgroundImage = `"url('${element.src}')";`;
        console.log(`"url('${element.src}')";`);
}

这是代码笔: https://codepen.io/vaughnick/pen/VygjZw

你必须改变这个"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';">
 

您需要删除 url() 周围的引号。

document.getElementById('message').style.backgroundImage = `url('${element.src}')`;
//                                                         ^                     ^ without
//                                                                                 "