我在使用JavaScript更改背景图片时遇到问题

时间:2019-09-22 22:31:37

标签: javascript

我正在执行Coursera作业,该作业要求我让JavaScript代码通过onmouseover事件更改背景图片,然后通过onmouseout事件将其恢复为正常状态,以及将每次发生事件时,图像都会放在最前面,但是最近几天我尝试了很多编码,这些代码根本无法工作,我也不知道为什么。

HTML:

<div id = "image">Hover over an image below to display here</div>

<img class = "preview" alt = "Beautiful kitten"
src = "https://images2.minutemediacdn.com/image/upload/c_crop,h_1193,w_2121,x_0,y_64/f_auto,q_auto,w_1100/v1565279671/shape/mentalfloss/578211-gettyimages-542930526.jpg"
onmouseover = "update(this)"
 onmouseout = "undo()"/>

<img class = "preview" alt = "Pretty Kitty" 
src = "https://www.thesprucepets.com/thmb/st2K40YnRkWUc3P_01lHYzflk7s=/3558x2363/filters:no_upscale():max_bytes(150000):strip_icc()/Cat-rolling-GettyImages-165893132-58ac5ef05f9b58a3c90a144f.jpg"
onmouserover = "update()" onmouseout = "undo()"/>

<img class = "preview" alt = "Baby cat"
src = "https://i.pinimg.com/originals/5b/8f/4c/5b8f4ca8916661d1c4310bed5e1b76b0.jpg" onmouseover = "update(this)" onmouseout = "undo()"/>

JS:

    var originalBackground;
function update(previewPic){
/* In this function I 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 
    */
   previewPic = document.getElementsByClassName("preview");
   document.getElementById("image").src = previewPic;

    document.getElementById("image").innerHTML = img.getAttribute("alt");


}


function undo(){

    document.getElementById("image").style.backgroundImage = "";

}

4 个答案:

答案 0 :(得分:1)

您所有的<img>元素都具有相同的类preview。调用document.getElementsByClassName("preview")时,您将获得三个元素的集合。

您需要获取鼠标悬停的特定元素。您已经使用参数this传递了该参数,但是在调用document.getElementsByClassName("preview")时覆盖了该值。

注意:您有错字onmouserover = "update()",请删除多余的r

function update(previewPic){
/* In this function I 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").setAttribute('style', 'background-image: url(' +  previewPic.getAttribute("src") + ')');
   document.getElementById("image").innerHTML = previewPic.getAttribute("alt");
}


function undo(){
    document.getElementById("image").style.backgroundImage = "";
    document.getElementById("image").title = "";
}
#image, 
.preview { 
  width : 100px; 
  min-height: 100px; 
  background-size: contain;
  background-repeat: no-repeat; 
}
<div id = "image">Hover over an image below to display here</div>

<img class = "preview" alt = "Beautiful kitten"
src = "https://images2.minutemediacdn.com/image/upload/c_crop,h_1193,w_2121,x_0,y_64/f_auto,q_auto,w_1100/v1565279671/shape/mentalfloss/578211-gettyimages-542930526.jpg"
onmouseover = "update(this)"
 onmouseout = "undo()"/>

<img class = "preview" alt = "Pretty Kitty" 
src = "https://www.thesprucepets.com/thmb/st2K40YnRkWUc3P_01lHYzflk7s=/3558x2363/filters:no_upscale():max_bytes(150000):strip_icc()/Cat-rolling-GettyImages-165893132-58ac5ef05f9b58a3c90a144f.jpg"
onmouseover = "update(this)" onmouseout = "undo()"/>

<img class = "preview" alt = "Baby cat"
src = "https://i.pinimg.com/originals/5b/8f/4c/5b8f4ca8916661d1c4310bed5e1b76b0.jpg" onmouseover = "update(this)" onmouseout = "undo()"/>

答案 1 :(得分:0)

我只是更改了您的JS函数,以使用正确的参数对其进行更新。为了实现 undo ,我发现您可能想存储任何onmouseover之前显示的先前文本。希望对您有帮助!

function update(previewPic){
   console.log('onmouseover');
   const image = document.getElementById("image");
   image._oldText = image.innerHTML;
   image.style.backgroundImage = `url(${previewPic.src})`;
   image.innerHTML = previewPic.getAttribute("alt");
}

function undo(){
  console.log('onmouseout');
  const image = document.getElementById("image");
  image.style.backgroundImage = "";
  image.innerHTML = image._oldText;
}
<div id="image">Hover over an image below to display here</div>

<img class="preview" alt="Beautiful kitten" style="width:100px;"
src="https://images2.minutemediacdn.com/image/upload/c_crop,h_1193,w_2121,x_0,y_64/f_auto,q_auto,w_1100/v1565279671/shape/mentalfloss/578211-gettyimages-542930526.jpg"
onmouseover="update(this)" onmouseout="undo()"/>

<img class="preview" alt="Baby cat" style="width:100px;"
src="https://i.pinimg.com/originals/5b/8f/4c/5b8f4ca8916661d1c4310bed5e1b76b0.jpg" onmouseover="update(this)" onmouseout="undo()"/>

答案 2 :(得分:0)

您可以采用多种方法来解决上述问题,但这是一种方法(使用ES2015 +语法)。

如果代码中似乎有任何不清楚或违反直觉的内容,请在下面的注释中提出问题,我可以解释代码的每个部分在做什么。

工作示例:

const mainImage = document.getElementById('image');
const previews = [... document.getElementsByClassName('preview')];

const update = (e) => {
  mainImage.style.backgroundImage = 'url("' + e.target.src + '")';
  mainImage.style.backgroundSize = 'contain';
  mainImage.style.backgroundRepeat = 'no-repeat';
  mainImage.style.backgroundPosition = 'center';
  mainImage.textContent = e.target.alt;
}

const undo = () => {
    mainImage.style.backgroundImage = '';
    mainImage.textContent = 'Hover over an image below to display here';
}

previews.forEach((preview) => {
  preview.addEventListener('mouseover', update, false);
  preview.addEventListener('mouseout', undo, false);
});
#image {
  float: left;
  width: 300px;
  height: 150px;
  text-align: center;
  text-shadow: 1px 1px 4px rgb(255, 255, 255), 1px -1px 4px rgb(255, 255, 255), -1px -1px 4px rgb(255, 255, 255), -1px 1px 4px rgb(255, 255, 255);
}

.preview {
  width: 100px;
}
<div id="image">Hover over an image below to display here</div>

<img class="preview" alt="Beautiful kitten"
src = "https://images2.minutemediacdn.com/image/upload/c_crop,h_1193,w_2121,x_0,y_64/f_auto,q_auto,w_1100/v1565279671/shape/mentalfloss/578211-gettyimages-542930526.jpg" />

<img class="preview" alt="Pretty Kitty" src = "https://www.thesprucepets.com/thmb/st2K40YnRkWUc3P_01lHYzflk7s=/3558x2363/filters:no_upscale():max_bytes(150000):strip_icc()/Cat-rolling-GettyImages-165893132-58ac5ef05f9b58a3c90a144f.jpg" />

<img class="preview" alt="Baby cat"
src = "https://i.pinimg.com/originals/5b/8f/4c/5b8f4ca8916661d1c4310bed5e1b76b0.jpg" />


  

问题: 您是否使用了const而不是function?如果是这样,为什么?

1)在Javascript的早期版本(2015年之前)中,我们声明了以下函数:

function myFunction() { 

  [... code here...]

}

在2015年以后的Javascript版本中(有时称为ES6+ES2015+),我们通常将函数声明为这样的变量:

var myFunction = () => {

  [... code here...]

}

这有几个优点(您现在不必真正担心),但要点是,它的功能与您惯用的语法相同...只是在括号function之前而不是() 之前,在括号中是一个粗箭头=>

当然,您会注意到我在上例中使用var声明了变量,而我在答案中使用了const

这又是因为,从2015年起的Javascript版本中,当我们声明变量(任何变量)时,我们通常使用关键字声明函数:

  • let
  • const

我们使用let(适用于将来可能会更改内容的变量)和const(适用于内容将始终保持不变的变量)。


  

问题:语法update = (e) => {是什么意思?

因此,从上面的答案中,我们现在看到:

const update = () => {}

几乎与以下内容相同:

function update() {}

因此,这里唯一需要了解的是e中的(e)

e的意思是:

任何函数可选地包含parameters-可以输入到函数中的数据变量。这是parens在声明函数时所做的事情-它们包含将在函数中处理的所有参数

通常,函数根本不需要任何参数,并且 是为什么当您看到声明的函数时,经常看到:()。这意味着将没有没有参数传递给该函数。

在这种情况下,e(有时被称为event,尽管可以被称为任何东西)是一个特殊的参数

无论何时创建事件监听器(如mouseovermouseout(还有clickchangeresizescroll),它始终存在等)

当您在事件监听器触发后运行的函数中引用event对象时,便可以访问许多真正有用的属性:

  • event.target
  • event.type
  • event.timeStamp

在这种情况下,我使用的是event.target(或e.target),以便在事件触发并运行该函数时,该函数知道 哪个图像 触发了该事件,因为该图像是事件目标


  

问题:引号中的多个引号是什么   mainImage.style.backgroundImage = 'url("' + e.target.src + '")';   是什么意思?

mainImage.style.backgroundImage = '[VALUE HERE]';

使用字符串值(包含在单引号background-image中)更新mainImage的CSS '样式。

我们可以看到,单引号属于javascript -它们包含javascript值。

如果我们事先知道要添加的图像的网址(并且始终相同),则可以编写:

mainImage.style.backgroundImage = 'url("my-image.jpg")';

在这里,单引号属于javascript -它们包含javascript值。

双引号属于CSS-它们包含CSS值my-image.jpg

我们现在可以进入更高级的步骤,在该步骤中我们事先不知道要添加的图像的URL。

值是:e.target.src

因此,以某种方式,我们需要将 that 表示为CSS值。

但是e.target.src在CSS中没有任何意义。

所以我们不能简单地写:

'url("e.target.src")'

相反(这是关键),我们必须打破CSS语法,添加变量,然后添加其余CSS语法。我们可以通过以下方式实现这一点:

 'url("'  +  e.target.src  +  '")'

这可以理解为:

'JS string contained in sinqle quotes' + actualJSValue + 'another string'

因此,最后一行的结尾为:

mainImage.style.backgroundImage = 'url("' + e.target.src + '")';

答案 3 :(得分:0)

希望这会有所帮助

<style>
.preview {
  width: 50px;
  height: 50px;
}

#image {
  width: 100px;
  height: 50px
}
</style>

<div id="image">Hover over an image below to display here</div>

<img class="preview" alt="Beautiful kitten" src="https://images2.minutemediacdn.com/image/upload/c_crop,h_1193,w_2121,x_0,y_64/f_auto,q_auto,w_1100/v1565279671/shape/mentalfloss/578211-gettyimages-542930526.jpg" onmouseover="update(this)" onmouseout="undo()" />

<img class="preview" alt="Pretty Kitty" src="https://www.thesprucepets.com/thmb/st2K40YnRkWUc3P_01lHYzflk7s=/3558x2363/filters:no_upscale():max_bytes(150000):strip_icc()/Cat-rolling-GettyImages-165893132-58ac5ef05f9b58a3c90a144f.jpg" onmouserover="update(this)" onmouseout="undo()" />

<img class="preview" alt="Baby cat" src="https://i.pinimg.com/originals/5b/8f/4c/5b8f4ca8916661d1c4310bed5e1b76b0.jpg" onmouseover="update(this)" onmouseout="undo()" />
<script>

  function update(previewPic) {
    let divWithIdImage = document.getElementById("image");
    divWithIdImage.style.backgroundImage = 'url(' + previewPic.src + ')';
    divWithIdImage.innerHTML = previewPic.alt;
  }


  function undo() {
    let divWithIdImage = document.getElementById("image");
    divWithIdImage.style.backgroundImage = "";
    divWithIdImage.innerHTML = 'Hover over an image below to display here'
  }

</script>