简体   繁体   English

当我 hover JS 中的另一个图像时,我想将 div 更改为背景图像

[英]I want to change the div to a background image when i hover the other image in JS

 function upDate(previewPic) { let bigImage = document.querySelector('#image'); let u = previewPic.src; bigImage.style.backgroundImage = "url(u)"; }
 <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()">

when i hover on the class preview i want to change the background image of my id ="image".当我在 class 预览上的 hover 时,我想更改我的 id="image" 的背景图像。 but my cose is not working it is showing但我的 cose 不工作它正在显示

当我悬停图像时输出

In your Javascript code, you call bigImage.style.backgroundImage = "url(u)";在您的 Javascript 代码中,您调用bigImage.style.backgroundImage = "url(u)"; which sets the div's backgroundImage style to url(u) .它将 div 的 backgroundImage 样式设置为url(u) In order to have u be replaced with the content of the variable u , you can use a template literal like so bigImage.style.backgroundImage = `url(${u})`;为了将u替换为变量u的内容,您可以使用如下模板文字bigImage.style.backgroundImage = `url(${u})`; Using the backticks around your string allows you to put js code inside of the string which will be evalauted and put inside of the string.在字符串周围使用反引号允许您将 js 代码放入字符串中,该字符串将被评估并放入字符串中。

You need to bind variable either concatenating "url(" + u +")" or using template literals url(${u}) , and also you need to add some width and height for div.您需要将变量连接起来"url(" + u +")"或使用模板文字url(${u}) ,还需要为 div 添加一些宽度和高度。

 function upDate(previewPic) { let bigImage = document.querySelector('#image'); let u = previewPic.src; bigImage.style.backgroundImage = `url(${u})`; } function unDo() { }
 #image { width: 100%; height: 50vh; background-repeat: no-repeat; }
 <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()">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM