如何更改从另一个元素向div添加alt文本



我正在尝试使用javascript更改id为image的div的alt文本和背景图像。

我尝试过使用document.getElementById('image').innerHTML = this.alt来更改文本,但它不起作用。

我也尝试过使用document.getElementById('image').style.backgroundImage = this.src

有人能为我提供一些见解吗?

function upDate(previewPic) {
document.getElementById('image').style.backgroundImage = this.src;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Photo Gallery</title>
<link rel="stylesheet" href="css/gallery.css">
<script src="js/gallery.js"></script>
</head>
<body>
<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()">
</body>
</html>

如@Toastrackenigma所述,函数中的javascript关键字this仅指函数上下文,而不是您要查找的previewPic参数。你可以在这里阅读更多关于它的信息。您可以在HTML中使用onmouseover="upDate(this)",因为HTML中的this关键字指的是图像,而JS中的this关键字则不是。

你要找的可能是这样的东西:

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

然而,正如本文所述,背景图像仅用于装饰,不应具有任何语义的含义,因此不应具有alt属性。您可能正在考虑div元素的title属性,该属性将在悬停时显示一个小工具提示。同样,你也可以使用

document.getElementById('image').title = previewPic.alt;

最新更新