我写了一个函数,应该将id =“image”的div的背景图像更改为正在悬停的当前图像。此外,它应该将innerHTML更改为图像的alt文本。
我写了一个函数upDate(previewPic),当有人在三个图像中的一个上悬停(onmousover)时触发。图像上方是id =“image”的div。 div应显示当前图像和替换文本。
然而,我似乎无法让它发挥作用。我做错了什么?
function upDate(previewPic){
/* In this function you should
1) change the url for the background image of the div with the id = "image"
to the source file of the preview image
2) Change the text of the div with the id = "image"
to the alt text of the preview image
*/
document.getElementById("image").style.backgroundImage =
url(previewPic.src);
document.getElementById("image").innerHTML =
previewPic.alt;
这是我的全部工作:
答案 0 :(得分:0)
您访问backgroundImage
属性,该属性需要为string
类型。所以只需将代码包装成引号即可。
答案 1 :(得分:0)
style.backgroundImage
应为字符串
使用ECMAScript 6(ES6)引入了一种新的文字,即template literals。
function upDate(previewPic){
/* In this function you should
1) change the url for the background image of the div with the id = "image"
to the source file of the preview image
2) Change the text of the div with the id = "image"
to the alt text of the preview image
*/
document.getElementById("image").style.backgroundImage = `url('${previewPic.src}')`;
document.getElementById("image").innerHTML = previewPic.alt;
}
答案 2 :(得分:0)
您好我已更新并分叉您的codepen;
实际上,您必须设置整个"网址('" +#14;""'"")引号中的部分。我也实现了unDo()。以下是您的codepen js的摘录;
/*Name this external file gallery.js*/
var imageDiv = document.getElementById("image");
var imageSrc = '';
var imageText = '';
function upDate(previewPic){
/* In this function you should
1) change the url for the background image of the div with the id = "image"
to the source file of the preview image
2) Change the text of the div with the id = "image"
to the alt text of the preview image
*/
imageSrc = imageDiv.style.backgroundImage;
imageText = imageDiv.innerHTML;
imageDiv.style.backgroundImage = "url('"+previewPic.src+"')";
imageDiv.innerHTML = previewPic.alt;
}
function unDo(){
/* In this function you should
1) Update the url for the background image of the div with the id = "image"
back to the orginal-image. You can use the css code to see what that original URL was
2) Change the text of the div with the id = "image"
back to the original text. You can use the html code to see what that original text was
*/
imageDiv.style.backgroundImage = imageSrc;
imageDiv.innerHTML = imageText;
}