如何用javascript中的图像src更改标识符的url?

How to change url of identifier with src of image in javascript?

我想将光标悬停在图像上并将其作为另一个 div 的背景图像显示。我在 js 中执行以下操作:

function upDate(previewPic){
document.getElementById("image").style.backgroundImage="url(previewPic.src)";
}

src 包含在线 link 所以不用担心。我想通过 id "image" 访问 div 并将其 bg 图片的 url 替换为我悬停的图片的 src。我进行了一个函数调用,将当前图像的对象发送给我。

完整代码如下:

function upDate(previewPic){
  document.getElementById("image").style.backgroundImage="url(previewPic.src)";
}
#image {
  line-height: 650px;
  width: 575px;
  height: 650px;
  border: 5px solid black;
  margin: 0 auto;
  background-color: #8e68ff;
  background-image: url('');
  background-repeat: no-repeat;
  color: #FFFFFF;
  text-align: center;
  background-size: 100%;
  margin-bottom: 25px;
  font-size: 150%;
}

.preview {
  width: 10%;
  margin-left: 17%;
  border: 10px solid black;
}
<div id="image">
  Hover over an image below to display here.
</div>

<img class="preview" alt="Styling with a Bandana" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg" onmouseover="upDate(this)" onmouseout="unDo()">

<img class="preview" alt="With My Boy" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon2.JPG" onmouseover="upDate(this)" onmouseout="unDo()">

<img class="preview" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon3.jpg" alt="Young Puppy" onmouseover="upDate(this)" onmouseout="unDo()">

您想应用如下内容CSS:

background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg");

但你实际上是这样做的:

background-image: url(previewPic.src);

这是您需要更新的 javascript 行,已更正字符串连接:

document.getElementById("image").style.backgroundImage= "url('" + previewPic.src + "')";

代码片段:

function upDate(previewPic){
  document.getElementById("image").style.backgroundImage= "url('" + previewPic.src + "')";
}
#image {
  line-height: 650px;
  width: 575px;
  height: 650px;
  border: 5px solid black;
  margin: 0 auto;
  background-color: #8e68ff;
  background-image: url('');
  background-repeat: no-repeat;
  color: #FFFFFF;
  text-align: center;
  background-size: 100%;
  margin-bottom: 25px;
  font-size: 150%;
}

.preview {
  width: 10%;
  margin-left: 17%;
  border: 10px solid black;
}
<div id="image">
  Hover over an image below to display here.
</div>

<img class="preview" alt="Styling with a Bandana" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg" onmouseover="upDate('https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg')" onmouseout="unDo()">

<img class="preview" alt="With My Boy" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon2.JPG" onmouseover="upDate('https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon2.JPG')" onmouseout="unDo()">

<img class="preview" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon3.jpg" alt="Young Puppy" onmouseover="upDate('https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon3.jpg')" onmouseout="unDo()">